1"""
2Normalized Redis command metadata.
3
4This module owns the record types for everything the client derives from a ``COMMAND``
5reply. ``CommandPolicies`` carries the request/response policies used for cluster routing;
6``CommandMetadata`` is the superset record that adds the inputs to the
7client-side-caching (CSC) eligibility rules.
8
9A command is cacheable only when it is ``readonly``, is not ``blocking``, takes at least one
10key name argument, and carries none of the ``nondeterministic_output``, ``script_runner`` or
11``dont_cache`` markers - see :func:`_is_client_side_cacheable`, which is the one normative
12implementation of those rules and also requires the source metadata to have been complete.
13Every boolean below therefore defaults to the fail-closed value, so a partially populated
14record is never mistaken for a cacheable one.
15
16``MetadataResolver`` serves those records by command name. Resolvers chain through
17``with_fallback``, first match wins, and an exhausted chain resolves to None - so an
18unknown command fails closed. A cluster client reads the routing policies off the resolved
19record; a client-side cache asks ``is_cacheable``, which applies the rules above to it. Either
20way a consumer needs a reference to nothing but the resolver.
21
22A record may also withhold its routing policies by leaving them None, which says that the
23metadata does not describe how to route the command and the client must resolve the target
24itself - see :func:`_to_command_policies`. The cacheability inputs of such a record are still
25authoritative, so withholding routing costs nothing on the caching side.
26
27``_STATIC_COMMAND_METADATA`` is the static resolver table, and the single source of truth for
28what this client routes by: the commands eligible for client-side caching plus the commands the
297.1.0 ``redis.commands.policies.STATIC_POLICIES`` table carried. That table is now a frozen,
30unread copy of its 7.1.0 self - edit routing here, never there. Values here are validated
31against a live
32``COMMAND`` reply - see the provenance note on the constant, which records the server it
33was checked against and the entries that diverge on purpose, before editing it by hand.
34"""
35
36from abc import ABC, abstractmethod
37from collections.abc import Mapping
38from dataclasses import dataclass, replace
39from enum import Enum
40from types import MappingProxyType
41
42__all__ = [
43 "AsyncBaseMetadataResolver",
44 "AsyncDynamicMetadataResolver",
45 "AsyncMetadataResolver",
46 "AsyncStaticMetadataResolver",
47 "BaseMetadataResolver",
48 "CommandMetadata",
49 "CommandMetadataRecordsCache",
50 "CommandPolicies",
51 "DynamicMetadataResolver",
52 "MetadataResolver",
53 "PolicyRecords",
54 "RequestPolicy",
55 "ResponsePolicy",
56 "StaticMetadataResolver",
57]
58
59
60class RequestPolicy(Enum):
61 ALL_NODES = "all_nodes"
62 ALL_SHARDS = "all_shards"
63 ALL_REPLICAS = "all_replicas"
64 MULTI_SHARD = "multi_shard"
65 SPECIAL = "special"
66 DEFAULT_KEYLESS = "default_keyless"
67 DEFAULT_KEYED = "default_keyed"
68 DEFAULT_NODE = "default_node"
69
70
71class ResponsePolicy(Enum):
72 ONE_SUCCEEDED = "one_succeeded"
73 ALL_SUCCEEDED = "all_succeeded"
74 AGG_LOGICAL_AND = "agg_logical_and"
75 AGG_LOGICAL_OR = "agg_logical_or"
76 AGG_MIN = "agg_min"
77 AGG_MAX = "agg_max"
78 AGG_SUM = "agg_sum"
79 SPECIAL = "special"
80 DEFAULT_KEYLESS = "default_keyless"
81 DEFAULT_KEYED = "default_keyed"
82
83
84class CommandPolicies:
85 """
86 The routing view of a command's metadata: how to dispatch it, how to aggregate replies.
87
88 Kept as a mutable class rather than folded into :class:`CommandMetadata` because this is
89 the shape that shipped in 7.1.0.
90
91 Compared by value, because a policy resolver serves the projection of the record it
92 proxies rather than a record a caller handed it - so identity does not hold, and a caller
93 matching what a resolver served against what it supplied has only the values to go by.
94 """
95
96 def __init__(
97 self,
98 request_policy: RequestPolicy = RequestPolicy.DEFAULT_KEYLESS,
99 response_policy: ResponsePolicy = ResponsePolicy.DEFAULT_KEYLESS,
100 ):
101 self.request_policy = request_policy
102 self.response_policy = response_policy
103
104 def __eq__(self, other: object) -> bool:
105 if not isinstance(other, CommandPolicies):
106 return NotImplemented
107
108 return (
109 self.request_policy == other.request_policy
110 and self.response_policy == other.response_policy
111 )
112
113 def __hash__(self) -> int:
114 # Defined alongside ``__eq__`` because Python would otherwise set it to None, which
115 # would make a type that shipped hashable in 7.1.0 unhashable.
116 return hash((self.request_policy, self.response_policy))
117
118 def __repr__(self) -> str:
119 return (
120 f"{type(self).__name__}(request_policy={self.request_policy!r}, "
121 f"response_policy={self.response_policy!r})"
122 )
123
124
125PolicyRecords = dict[str, dict[str, CommandPolicies]]
126
127
128@dataclass(frozen=True, slots=True)
129class CommandMetadata:
130 """
131 Normalized metadata for a single Redis command or container subcommand.
132
133 Instances are immutable so the static table below can be shared without copying. A
134 resolver that refines a record builds a new one with :func:`dataclasses.replace`.
135
136 Attributes:
137 request_policy:
138 How the cluster client should route the command. Derived from the
139 ``request_policy`` command tip, defaulting to keyed/keyless based on whether
140 the command takes keys. None means the record withholds its routing opinion:
141 the metadata does not describe how to route this command, so the client resolves
142 the target itself. That is distinct from ``DEFAULT_KEYLESS``, which is a routing
143 decision - send the command to any one node.
144 response_policy:
145 How the cluster client should aggregate replies from several nodes. Derived
146 from the ``response_policy`` command tip, with the same default. None has the
147 same meaning as it does for ``request_policy``; the two are withheld together,
148 because a policy resolver serves them as one record.
149 is_readonly:
150 Whether the command has the ``readonly`` command flag. Required for
151 cacheability.
152 is_blocking:
153 Whether the command has the ``blocking`` command flag, which marks a command
154 that may block the connection until data arrives. A blocking read serves the
155 reply its caller waited for rather than a snapshot of keyspace state, so
156 re-serving it from a cache would break the command's execution-time contract:
157 ``XREAD BLOCK`` in a loop would stop blocking once a timed-out reply was cached.
158 The exclusion is by command name, so ``XREAD`` is ineligible even when a
159 particular call omits ``BLOCK``. It is the only readonly, keyed command the flag
160 excludes.
161 has_key_argument:
162 Whether the command accepts at least one Redis key name argument. True when
163 ``key_specifications`` holds at least one spec not flagged ``not_key``,
164 falling back to ``first_key_pos > 0 and step_count > 0`` when key specs are
165 absent. ``last_key_pos`` is never consulted: it is ``-1`` for variadic
166 commands and must not disqualify one.
167
168 This is not the inverse of ``_is_keyless_command``, which lets
169 ``first_key_pos`` decide whenever it is positive and so reports SPUBLISH, whose
170 only key spec is a ``not_key`` shard channel, as keyed. It is also recorded
171 independently of ``request_policy``, because a
172 command tip overwrites the keyed/keyless default, after which the resolved
173 policy no longer indicates whether the command takes keys.
174 has_nondeterministic_output:
175 Whether the command has the ``nondeterministic_output`` command tip, which
176 marks a command whose reply may differ between calls over the same keyspace
177 state. Matched exactly rather than by prefix: ``nondeterministic_output_order``
178 is a distinct tip, denoting only that element order varies.
179 is_script_runner:
180 Whether the command has the ``script_runner`` command flag, which marks a
181 command that executes a user-supplied script or function. Reported by Redis
182 8.10 and later; earlier servers do not report the flag at all.
183 is_dont_cache:
184 Whether the command has the ``dont_cache`` command tip, which marks a command
185 whose reply the server states must not be cached client-side. It is a negative
186 override: it decides on its own, even when every positive rule matches.
187 has_complete_metadata:
188 Whether the source metadata was complete enough to trust, meaning the command
189 flags were present *and* the ``tips`` key was present. ``COMMAND`` replies
190 older than Redis 7.0 carry neither ``tips`` nor ``key_specifications``, which
191 makes ``nondeterministic_output`` and ``dont_cache`` undetectable. An empty
192 tips list is a real answer; a missing tips key is not. An incomplete record
193 must not be treated as authoritative.
194 """
195
196 request_policy: RequestPolicy | None = RequestPolicy.DEFAULT_KEYLESS
197 response_policy: ResponsePolicy | None = ResponsePolicy.DEFAULT_KEYLESS
198 is_readonly: bool = False
199 is_blocking: bool = False
200 has_key_argument: bool = False
201 has_nondeterministic_output: bool = False
202 is_script_runner: bool = False
203 is_dont_cache: bool = False
204 has_complete_metadata: bool = False
205
206
207CommandMetadataRecordsCache = Mapping[str, Mapping[str, CommandMetadata]]
208"""Command metadata keyed by module name, then by command name.
209
210Mirrors the shape of ``PolicyRecords``: non-module commands live under ``"core"``, module
211commands under their lowercased prefix (``"json"``, ``"ts"``, ``"ft"``), and container
212subcommands under their space-joined name (``"memory usage"``), which is the form
213``execute_command`` receives as ``args[0]``.
214"""
215
216
217def _lowercase_keyed(
218 records: CommandMetadataRecordsCache,
219) -> CommandMetadataRecordsCache:
220 """
221 Key the given records lowercase, which is how :func:`_split_command_name` looks one up.
222
223 Records built from a ``COMMAND`` reply already are - both parsers lowercase every command
224 name as they read it - so the common case returns the argument untouched rather than
225 rebuilding it. Caller-supplied records carry whatever spelling the caller chose, and a
226 resolver that silently answers nothing for a table keyed ``"ZCOUNT"`` would be worse than
227 one that normalizes it.
228 """
229 if all(
230 module_name == module_name.lower()
231 and all(command == command.lower() for command in commands)
232 for module_name, commands in records.items()
233 ):
234 return records
235
236 return {
237 module_name.lower(): {
238 command.lower(): metadata for command, metadata in commands.items()
239 }
240 for module_name, commands in records.items()
241 }
242
243
244def _split_command_name(command_name: str) -> tuple[str, str]:
245 """
246 Split a command name into the ``(module, command)`` pair the record tables are keyed by.
247
248 Non-module commands resolve under ``"core"``. Container subcommands are not split here:
249 they arrive space-joined (``"memory usage"``) and are looked up under that whole name.
250
251 The name is lowercased, because the record tables are keyed lowercase while callers
252 spell a command the way they send it: the cluster client lowercases before resolving,
253 but the client-side cache is handed the command name as the command methods spell it
254 (``"GET"``, ``"JSON.GET"``, ``"MEMORY USAGE"``).
255
256 Raises:
257 ValueError: If the name carries more than one module prefix.
258 """
259 parts = command_name.lower().split(".")
260
261 if len(parts) > 2:
262 raise ValueError(f"Wrong command or module name: {command_name}")
263
264 if len(parts) == 2:
265 return parts[0], parts[1]
266
267 return "core", parts[0]
268
269
270# Upper bound on each of a resolver's memos. Far above the number of distinct command names
271# an application issues - the whole core surface plus every module's is a few hundred - but
272# bounded, because the default resolver a client gets is a single instance evaluated at import
273# and shared by every client in the process, ``execute_command`` accepts an arbitrary command
274# name, and a name that resolves to nothing is memoized too. Past the cap the views still
275# answer correctly; they just recompute.
276_MEMO_MAX_ENTRIES = 4096
277
278# Commands whose ``readonly`` flag is not sufficient to make replica routing safe. TOUCH
279# changes key idle-time state even though Redis reports it readonly, so it must continue to
280# reach a primary. Keep this exception narrow: caller-supplied metadata remains authoritative
281# for ordinary core and module reads.
282#
283# Loaded into every resolver's ``_replica_safe`` memo at construction, which is the whole
284# mechanism: the entry is in place before any command is looked up, so these answer from the
285# same single dict lookup as every other command and ``is_replica_safe`` needs no test of its
286# own. Nothing clears or evicts from that memo - the cap only declines to add - so a seeded
287# entry cannot be lost. Names are lower case, the form command names are keyed by throughout
288# this module.
289_REPLICA_UNSAFE_COMMANDS = frozenset({"touch"})
290
291
292class MetadataResolver(ABC):
293 @abstractmethod
294 def resolve(self, command_name: str) -> CommandMetadata | None:
295 """
296 Resolves the command name and determines the associated command metadata.
297
298 Args:
299 command_name: The name of the command to resolve, in any case.
300
301 Returns:
302 CommandMetadata: The metadata associated with the specified command, or None
303 when no resolver in the chain knows the command.
304 """
305 pass
306
307 @abstractmethod
308 def resolve_policies(self, command_name: str) -> CommandPolicies | None:
309 """
310 Resolves the command name and determines the associated routing policies.
311
312 The routing view of :meth:`resolve`: the request/response policies the resolved
313 record carries, and nothing else about it.
314
315 Args:
316 command_name: The name of the command to resolve, in any case.
317
318 Returns:
319 CommandPolicies: The policies associated with the specified command, or None
320 when no resolver in the chain knows the command.
321 """
322 pass
323
324 @abstractmethod
325 def is_cacheable(self, command_name: str) -> bool:
326 """
327 Determines whether the reply of a command may be served from a client-side cache.
328
329 The client-side-caching view of :meth:`resolve`, decided by
330 :func:`_is_client_side_cacheable`. Fails closed: an unknown command, a name the
331 record tables cannot be keyed by, and a record built from incomplete metadata all
332 resolve to False.
333
334 Args:
335 command_name: The name of the command to check, in any case.
336
337 Returns:
338 bool: True only when every eligibility rule is satisfied.
339 """
340 pass
341
342 @abstractmethod
343 def is_replica_safe(self, command_name: str) -> bool:
344 """
345 Determines whether a command is safe to execute on a replica.
346
347 Args:
348 command_name: The name of the command to check, in any case.
349
350 Returns:
351 bool: True if the command is replica safe.
352 """
353 pass
354
355 @abstractmethod
356 def is_trackable_read(self, command_name: str) -> bool:
357 """
358 Determines whether the server would remember this command's keys while tracking.
359
360 The server-side-tracking view of :meth:`resolve`, decided by
361 :func:`_is_trackable_read`. Never affects what may be stored: it only decides whether
362 a ``CLIENT CACHING NO`` in front of a read is worth sending under ``optout`` tracking.
363 When in doubt it returns False, so the ``NO`` is skipped and the server keeps
364 tracking the keys. That is the safe side: an extra tracked key only costs an entry in
365 the server's invalidation table, but a stored reply that the server does not track is
366 never invalidated and can go stale.
367
368 Args:
369 command_name: The name of the command to check, in any case.
370
371 Returns:
372 bool: True only when the command carries the ``readonly`` command flag.
373 """
374 pass
375
376 @abstractmethod
377 def with_fallback(self, fallback: "MetadataResolver") -> "MetadataResolver":
378 """
379 Factory method to instantiate a metadata resolver with a fallback resolver.
380
381 Args:
382 fallback: Fallback resolver
383
384 Returns:
385 MetadataResolver: Returns a new metadata resolver with the specified fallback resolver.
386 """
387 pass
388
389
390class AsyncMetadataResolver(ABC):
391 @abstractmethod
392 async def resolve(self, command_name: str) -> CommandMetadata | None:
393 """
394 Resolves the command name and determines the associated command metadata.
395
396 Args:
397 command_name: The name of the command to resolve, in any case.
398
399 Returns:
400 CommandMetadata: The metadata associated with the specified command, or None
401 when no resolver in the chain knows the command.
402 """
403 pass
404
405 @abstractmethod
406 async def resolve_policies(self, command_name: str) -> CommandPolicies | None:
407 """
408 Resolves the command name and determines the associated routing policies.
409
410 The routing view of :meth:`resolve`: the request/response policies the resolved
411 record carries, and nothing else about it.
412
413 Args:
414 command_name: The name of the command to resolve, in any case.
415
416 Returns:
417 CommandPolicies: The policies associated with the specified command, or None
418 when no resolver in the chain knows the command.
419 """
420 pass
421
422 @abstractmethod
423 async def is_cacheable(self, command_name: str) -> bool:
424 """
425 Determines whether the reply of a command may be served from a client-side cache.
426
427 The client-side-caching view of :meth:`resolve`, decided by
428 :func:`_is_client_side_cacheable`. Fails closed: an unknown command, a name the
429 record tables cannot be keyed by, and a record built from incomplete metadata all
430 resolve to False.
431
432 Args:
433 command_name: The name of the command to check, in any case.
434
435 Returns:
436 bool: True only when every eligibility rule is satisfied.
437 """
438 pass
439
440 @abstractmethod
441 async def is_replica_safe(self, command_name: str) -> bool:
442 """
443 Determines whether a command is safe to execute on a replica.
444
445 Args:
446 command_name: The name of the command to check, in any case.
447
448 Returns:
449 bool: True if the command is replica safe.
450 """
451 pass
452
453 @abstractmethod
454 async def is_trackable_read(self, command_name: str) -> bool:
455 """
456 Determines whether the server would remember this command's keys while tracking.
457
458 The server-side-tracking view of :meth:`resolve`, decided by
459 :func:`_is_trackable_read`. Never affects what may be stored: it only decides whether
460 a ``CLIENT CACHING NO`` in front of a read is worth sending under ``optout`` tracking.
461 When in doubt it returns False, so the ``NO`` is skipped and the server keeps
462 tracking the keys. That is the safe side: an extra tracked key only costs an entry in
463 the server's invalidation table, but a stored reply that the server does not track is
464 never invalidated and can go stale.
465
466 Args:
467 command_name: The name of the command to check, in any case.
468
469 Returns:
470 bool: True only when the command carries the ``readonly`` command flag.
471 """
472 pass
473
474 @abstractmethod
475 def with_fallback(
476 self, fallback: "AsyncMetadataResolver"
477 ) -> "AsyncMetadataResolver":
478 """
479 Factory method to instantiate an async metadata resolver with a fallback resolver.
480
481 Args:
482 fallback: Fallback resolver
483
484 Returns:
485 AsyncMetadataResolver: Returns a new metadata resolver with the specified fallback resolver.
486 """
487 pass
488
489
490class BaseMetadataResolver(MetadataResolver):
491 """
492 Base class for metadata resolvers.
493
494 Lookup is first-match-wins: a command the records do not carry falls through to the
495 fallback resolver, and a chain that ends without a match resolves to None. Besides the
496 whole record, each consumer gets the view it needs of the same resolved metadata:
497 ``resolve_policies`` for cluster routing, ``is_cacheable`` for client-side caching.
498
499 Both views are memoized under the lowercased command name, so every spelling of one
500 command - ``GET`` as the command methods write it, ``get`` as the cluster client lowers it
501 - shares a single entry instead of taking one each. The metadata a resolver serves is a
502 snapshot taken when the resolver is built, so a command's view cannot change, and the memo
503 keeps the record lookup, the projection and the walk down the fallback chain off the
504 command execution path. Concurrent resolves of the same command may each compute it once;
505 the memo is idempotent, so the duplicated work is harmless. The memos grow with the set of
506 distinct commands a caller asks about, and are capped at ``_MEMO_MAX_ENTRIES`` so that a
507 caller asking about unbounded many names - a name that resolves to nothing is memoized
508 too - cannot grow them without bound.
509 """
510
511 def __init__(
512 self,
513 metadata: CommandMetadataRecordsCache,
514 fallback: MetadataResolver | None = None,
515 ) -> None:
516 self._metadata = metadata
517 self._fallback = fallback
518 self._policies: dict[str, CommandPolicies | None] = {}
519 self._cacheable: dict[str, bool] = {}
520 self._replica_safe: dict[str, bool] = {
521 cmd: False for cmd in _REPLICA_UNSAFE_COMMANDS
522 }
523 # No ``_REPLICA_UNSAFE_COMMANDS`` pre-seed: trackability is the readonly flag alone,
524 # and TOUCH - the one command that seed excludes - is precisely the trackable read
525 # ``optout`` most wants to exempt.
526 self._trackable_read: dict[str, bool] = {}
527
528 def resolve(self, command_name: str) -> CommandMetadata | None:
529 module, command = _split_command_name(command_name)
530
531 commands = self._metadata.get(module)
532 metadata = commands.get(command) if commands is not None else None
533
534 if metadata is None:
535 if self._fallback is not None:
536 return self._fallback.resolve(command_name)
537 return None
538
539 return metadata
540
541 def resolve_policies(self, command_name: str) -> CommandPolicies | None:
542 # Memoized under the lowercased name, so the spellings of one command share an
543 # entry rather than taking one each. ``resolve`` is still asked with the name as
544 # given, so an unresolvable one is reported the way the caller spelled it.
545 memo_key = command_name.lower()
546
547 try:
548 return self._policies[memo_key]
549 except KeyError:
550 pass
551
552 metadata = self.resolve(command_name)
553 policies = _to_command_policies(metadata) if metadata is not None else None
554
555 if len(self._policies) < _MEMO_MAX_ENTRIES:
556 self._policies[memo_key] = policies
557
558 return policies
559
560 def is_cacheable(self, command_name: str) -> bool:
561 # A name the record tables cannot be keyed by is not a command this client can decide
562 # on. Fail closed rather than raise into the command execution path, where a raw
563 # command with such a name must still reach the server and come back with the
564 # server's own error. ``execute_command`` accepts an arbitrary first argument, and a
565 # non-str one - ``bytes``, which the request encoder accepts - reaches here
566 # unchanged; it is refused rather than decoded, because deciding it would start
567 # caching a command whose name this client never resolved.
568 if not isinstance(command_name, str):
569 return False
570
571 # Memoized under the lowercased name, so the spellings of one command share an
572 # entry rather than taking one each.
573 memo_key = command_name.lower()
574
575 try:
576 return self._cacheable[memo_key]
577 except KeyError:
578 pass
579
580 try:
581 metadata = self.resolve(command_name)
582 except ValueError:
583 # More than one module prefix, which ``_split_command_name`` refuses.
584 metadata = None
585
586 cacheable = _is_client_side_cacheable(metadata)
587
588 if len(self._cacheable) < _MEMO_MAX_ENTRIES:
589 self._cacheable[memo_key] = cacheable
590
591 return cacheable
592
593 def is_replica_safe(self, command_name: str) -> bool:
594 if not isinstance(command_name, str):
595 return False
596
597 memo_key = command_name.lower()
598
599 try:
600 return self._replica_safe[memo_key]
601 except KeyError:
602 pass
603
604 try:
605 metadata = self.resolve(command_name)
606 except ValueError:
607 metadata = None
608
609 replica_safe = _is_replica_safe(metadata)
610
611 if len(self._replica_safe) < _MEMO_MAX_ENTRIES:
612 self._replica_safe[memo_key] = replica_safe
613
614 return replica_safe
615
616 def is_trackable_read(self, command_name: str) -> bool:
617 if not isinstance(command_name, str):
618 return False
619
620 memo_key = command_name.lower()
621
622 try:
623 return self._trackable_read[memo_key]
624 except KeyError:
625 pass
626
627 try:
628 metadata = self.resolve(command_name)
629 except ValueError:
630 metadata = None
631
632 trackable_read = _is_trackable_read(metadata)
633
634 if len(self._trackable_read) < _MEMO_MAX_ENTRIES:
635 self._trackable_read[memo_key] = trackable_read
636
637 return trackable_read
638
639 @abstractmethod
640 def with_fallback(self, fallback: "MetadataResolver") -> "MetadataResolver":
641 pass
642
643
644class AsyncBaseMetadataResolver(AsyncMetadataResolver):
645 """
646 Async base class for metadata resolvers.
647
648 Lookup is first-match-wins: a command the records do not carry falls through to the
649 fallback resolver, and a chain that ends without a match resolves to None. Besides the
650 whole record, each consumer gets the view it needs of the same resolved metadata:
651 ``resolve_policies`` for cluster routing, ``is_cacheable`` for client-side caching.
652
653 Both views are memoized under the lowercased command name, so every spelling of one
654 command - ``GET`` as the command methods write it, ``get`` as the cluster client lowers it
655 - shares a single entry instead of taking one each. The metadata a resolver serves is a
656 snapshot taken when the resolver is built, so a command's view cannot change, and the memo
657 keeps the record lookup, the projection and the walk down the fallback chain off the
658 command execution path. Concurrent resolves of the same command may each compute it once;
659 the memo is idempotent, so the duplicated work is harmless. The memos grow with the set of
660 distinct commands a caller asks about, and are capped at ``_MEMO_MAX_ENTRIES`` so that a
661 caller asking about unbounded many names - a name that resolves to nothing is memoized
662 too - cannot grow them without bound.
663 """
664
665 def __init__(
666 self,
667 metadata: CommandMetadataRecordsCache,
668 fallback: AsyncMetadataResolver | None = None,
669 ) -> None:
670 self._metadata = metadata
671 self._fallback = fallback
672 self._policies: dict[str, CommandPolicies | None] = {}
673 self._cacheable: dict[str, bool] = {}
674 self._replica_safe: dict[str, bool] = {
675 cmd: False for cmd in _REPLICA_UNSAFE_COMMANDS
676 }
677 # No ``_REPLICA_UNSAFE_COMMANDS`` pre-seed: trackability is the readonly flag alone,
678 # and TOUCH - the one command that seed excludes - is precisely the trackable read
679 # ``optout`` most wants to exempt.
680 self._trackable_read: dict[str, bool] = {}
681
682 async def resolve(self, command_name: str) -> CommandMetadata | None:
683 module, command = _split_command_name(command_name)
684
685 commands = self._metadata.get(module)
686 metadata = commands.get(command) if commands is not None else None
687
688 if metadata is None:
689 if self._fallback is not None:
690 return await self._fallback.resolve(command_name)
691 return None
692
693 return metadata
694
695 async def resolve_policies(self, command_name: str) -> CommandPolicies | None:
696 # Memoized under the lowercased name, so the spellings of one command share an
697 # entry rather than taking one each. ``resolve`` is still asked with the name as
698 # given, so an unresolvable one is reported the way the caller spelled it.
699 memo_key = command_name.lower()
700
701 try:
702 return self._policies[memo_key]
703 except KeyError:
704 pass
705
706 metadata = await self.resolve(command_name)
707 policies = _to_command_policies(metadata) if metadata is not None else None
708
709 if len(self._policies) < _MEMO_MAX_ENTRIES:
710 self._policies[memo_key] = policies
711
712 return policies
713
714 async def is_cacheable(self, command_name: str) -> bool:
715 # A name the record tables cannot be keyed by is not a command this client can decide
716 # on. Fail closed rather than raise into the command execution path, where a raw
717 # command with such a name must still reach the server and come back with the
718 # server's own error. ``execute_command`` accepts an arbitrary first argument, and a
719 # non-str one - ``bytes``, which the request encoder accepts - reaches here
720 # unchanged; it is refused rather than decoded, because deciding it would start
721 # caching a command whose name this client never resolved.
722 if not isinstance(command_name, str):
723 return False
724
725 # Memoized under the lowercased name, so the spellings of one command share an
726 # entry rather than taking one each.
727 memo_key = command_name.lower()
728
729 try:
730 return self._cacheable[memo_key]
731 except KeyError:
732 pass
733
734 try:
735 metadata = await self.resolve(command_name)
736 except ValueError:
737 # More than one module prefix, which ``_split_command_name`` refuses.
738 metadata = None
739
740 cacheable = _is_client_side_cacheable(metadata)
741
742 if len(self._cacheable) < _MEMO_MAX_ENTRIES:
743 self._cacheable[memo_key] = cacheable
744
745 return cacheable
746
747 async def is_replica_safe(self, command_name: str) -> bool:
748 if not isinstance(command_name, str):
749 return False
750
751 memo_key = command_name.lower()
752
753 try:
754 return self._replica_safe[memo_key]
755 except KeyError:
756 pass
757
758 try:
759 metadata = await self.resolve(command_name)
760 except ValueError:
761 metadata = None
762
763 replica_safe = _is_replica_safe(metadata)
764
765 if len(self._replica_safe) < _MEMO_MAX_ENTRIES:
766 self._replica_safe[memo_key] = replica_safe
767
768 return replica_safe
769
770 async def is_trackable_read(self, command_name: str) -> bool:
771 if not isinstance(command_name, str):
772 return False
773
774 memo_key = command_name.lower()
775
776 try:
777 return self._trackable_read[memo_key]
778 except KeyError:
779 pass
780
781 try:
782 metadata = await self.resolve(command_name)
783 except ValueError:
784 metadata = None
785
786 trackable_read = _is_trackable_read(metadata)
787
788 if len(self._trackable_read) < _MEMO_MAX_ENTRIES:
789 self._trackable_read[memo_key] = trackable_read
790
791 return trackable_read
792
793 @abstractmethod
794 def with_fallback(
795 self, fallback: "AsyncMetadataResolver"
796 ) -> "AsyncMetadataResolver":
797 pass
798
799
800class DynamicMetadataResolver(BaseMetadataResolver):
801 """
802 Resolves metadata dynamically based on the provided metadata records
803 (they can be extracted either from COMMAND output, or provided by user).
804
805 Note: Takes the records rather than the parser that produced them, so that this and
806 ``AsyncDynamicMetadataResolver`` accept the same argument: the async parser's
807 ``get_commands_metadata_cache`` is a coroutine and cannot be awaited in a constructor, so records
808 are the one shape both stacks can be built from. :func:`_load_commands_metadata_cache` turns a
809 parser into records at the one place that owns one, ``DynamicPolicyResolver``.
810 """
811
812 def __init__(
813 self,
814 metadata_records: CommandMetadataRecordsCache,
815 fallback: MetadataResolver | None = None,
816 ) -> None:
817 """
818 Parameters:
819 metadata_records (CommandMetadataRecordsCache): Command metadata records,
820 keyed the way ``CommandMetadataRecordsCache`` documents. Keys are
821 lowercased if they are not already, because that is how a resolved
822 command name is looked up.
823 fallback (Optional[MetadataResolver]): An optional resolver to be used when the
824 primary metadata cannot handle a specific request.
825 """
826 super().__init__(_lowercase_keyed(metadata_records), fallback)
827
828 def with_fallback(self, fallback: "MetadataResolver") -> "MetadataResolver":
829 return DynamicMetadataResolver(self._metadata, fallback)
830
831
832class StaticMetadataResolver(BaseMetadataResolver):
833 """
834 Resolves metadata from a static list, provided by the library,
835 containing command metadata records.
836 """
837
838 def __init__(self, fallback: MetadataResolver | None = None) -> None:
839 """
840 Parameters:
841 fallback (Optional[MetadataResolver]): An optional fallback metadata resolver
842 used for resolving metadata if static metadata is inadequate.
843 """
844 super().__init__(_STATIC_COMMAND_METADATA, fallback)
845
846 def with_fallback(self, fallback: "MetadataResolver") -> "MetadataResolver":
847 return StaticMetadataResolver(fallback)
848
849
850class AsyncDynamicMetadataResolver(AsyncBaseMetadataResolver):
851 """
852 Async version of DynamicMetadataResolver.
853
854 Takes the records rather than the parser that produced them, because
855 ``AsyncCommandsParser.get_commands_metadata_cache`` is a coroutine and cannot be awaited in a
856 constructor.
857 """
858
859 def __init__(
860 self,
861 metadata_records: CommandMetadataRecordsCache,
862 fallback: AsyncMetadataResolver | None = None,
863 ) -> None:
864 """
865 Parameters:
866 metadata_records (CommandMetadataRecordsCache): Command metadata records,
867 keyed the way ``CommandMetadataRecordsCache`` documents. Keys are
868 lowercased if they are not already, because that is how a resolved
869 command name is looked up.
870 fallback (Optional[AsyncMetadataResolver]): An optional resolver to be used when the
871 primary metadata cannot handle a specific request.
872 """
873 super().__init__(_lowercase_keyed(metadata_records), fallback)
874
875 def with_fallback(
876 self, fallback: "AsyncMetadataResolver"
877 ) -> "AsyncMetadataResolver":
878 return AsyncDynamicMetadataResolver(self._metadata, fallback)
879
880
881class AsyncStaticMetadataResolver(AsyncBaseMetadataResolver):
882 """
883 Async version of StaticMetadataResolver.
884 """
885
886 def __init__(self, fallback: AsyncMetadataResolver | None = None) -> None:
887 """
888 Parameters:
889 fallback (Optional[AsyncMetadataResolver]): An optional fallback metadata resolver
890 used for resolving metadata if static metadata is inadequate.
891 """
892 super().__init__(_STATIC_COMMAND_METADATA, fallback)
893
894 def with_fallback(
895 self, fallback: "AsyncMetadataResolver"
896 ) -> "AsyncMetadataResolver":
897 return AsyncStaticMetadataResolver(fallback)
898
899
900def _to_command_policies(metadata: CommandMetadata) -> CommandPolicies | None:
901 """
902 Project a single metadata record down to the routing policies a policy resolver serves.
903
904 Drops every field a ``CommandPolicies`` record does not carry, so the policies a
905 command routes by stay derived from its metadata rather than tracked beside it.
906
907 A record that withholds its routing policies projects to None, which a policy resolver
908 reports the same way it reports a command it does not carry. Withholding therefore
909 reproduces, exactly, what a command absent from the records resolves to: a policy-level
910 fallback still gets its turn, and a resolver with none leaves the cluster client to resolve
911 the target itself - which for a ``movablekeys`` command is the only path that finds its
912 keys. The *metadata* chain is not re-walked, though: the record was found, so a metadata
913 resolver behind this one is never asked, and cannot answer with the very policies the
914 record withholds.
915 """
916 if metadata.request_policy is None or metadata.response_policy is None:
917 return None
918
919 return CommandPolicies(
920 request_policy=metadata.request_policy,
921 response_policy=metadata.response_policy,
922 )
923
924
925def _is_client_side_cacheable(metadata: CommandMetadata | None) -> bool:
926 """
927 Decide whether the reply of the command a record describes may be cached client-side.
928
929 The one normative implementation of the eligibility rules, applied in the order they are
930 specified. Every rule is a veto, so the verdict does not depend on the order; the order
931 is kept to match the specification.
932
933 Takes ``None`` - what an exhausted resolver chain resolves to - so the unknown-command
934 case is decided here as well, rather than by every caller.
935
936 An incomplete record is refused for the same reason an unknown command is: a ``COMMAND``
937 reply that carries no tips cannot express ``nondeterministic_output`` or ``dont_cache``,
938 so a record built from one does not prove the command is cacheable. Note that a resolver
939 answers from the first record it finds, so an incomplete record decides the command even
940 when a complete one sits behind it in the chain - an override table therefore belongs in
941 front of the resolver that may serve incomplete records, not behind it.
942 """
943 if metadata is None or not metadata.has_complete_metadata:
944 return False
945
946 # A negative override: the server states the reply must not be cached, which decides on
947 # its own even when every positive rule matches.
948 if metadata.is_dont_cache:
949 return False
950
951 if not metadata.is_readonly:
952 return False
953
954 if metadata.is_blocking:
955 return False
956
957 if not metadata.has_key_argument:
958 return False
959
960 if metadata.has_nondeterministic_output:
961 return False
962
963 if metadata.is_script_runner:
964 return False
965
966 return True
967
968
969def _is_replica_safe(metadata: CommandMetadata | None) -> bool:
970 """
971 Decide whether a command is safe to execute on a replica based on the readonly flag.
972
973 Takes ``None`` - what an exhausted resolver chain resolves to - so the
974 unknown-command case is decided here as well.
975 """
976 if metadata is None:
977 return False
978
979 return metadata.is_readonly
980
981
982def _is_trackable_read(metadata: CommandMetadata | None) -> bool:
983 """
984 Decide whether the server would remember the keys of the command a record describes.
985
986 The ``readonly`` command flag alone, because that plus the key names of the invocation is
987 the whole gate the server applies before it records a read against a tracking client. The
988 negative signals that make a command ineligible to store do not enter it: ``XPENDING`` is
989 tipped ``nondeterministic_output`` and ``TOUCH`` is tipped ``dont_cache``, and the server
990 tracks both.
991
992 Deliberately does not require ``has_complete_metadata``, unlike
993 :func:`_is_client_side_cacheable`: the readonly flag comes from the command flags, which
994 every ``COMMAND`` reply carries, and only the tips can be missing.
995
996 Takes ``None`` - what an exhausted resolver chain resolves to - so the unknown-command
997 case is decided here as well.
998 """
999 if metadata is None:
1000 return False
1001
1002 return metadata.is_readonly
1003
1004
1005def _build_commands_metadata_cache_from_policies(
1006 policy_records: PolicyRecords,
1007) -> CommandMetadataRecordsCache:
1008 """
1009 Build the metadata records cache from policy records.
1010
1011 Unlike ``_build_commands_metadata_cache``, which builds the cache from a raw ``COMMAND``
1012 reply, this lifts the narrower 7.1.0 routing view into the same shape.
1013
1014 Only the routing policies of each command are known, so every other field keeps its
1015 fail-closed default. This backs the ``PolicyRecords`` arguments of the policy resolvers:
1016 a resolver built from policy records serves exactly the policies it was given, and
1017 reports no command as client-side-cacheable, which is the conservative answer for
1018 metadata that was never supplied.
1019
1020 Keys are lowercased on the way through - the records are rebuilt here anyway - because
1021 that is how a resolved command name is looked up.
1022 """
1023 return {
1024 module_name.lower(): {
1025 command_name.lower(): CommandMetadata(
1026 request_policy=policies.request_policy,
1027 response_policy=policies.response_policy,
1028 )
1029 for command_name, policies in commands.items()
1030 }
1031 for module_name, commands in policy_records.items()
1032 }
1033
1034
1035def _load_commands_metadata_cache(
1036 commands_parser: object,
1037) -> CommandMetadataRecordsCache:
1038 """
1039 Load the metadata records cache of a ``COMMAND`` parser.
1040
1041 ``get_commands_metadata_cache`` is what a parser serves, and is what this loads.
1042
1043 The ``get_command_policies`` branch is a backwards-compatibility shim, not a second
1044 supported shape. ``DynamicPolicyResolver`` called nothing but that method in 7.1.0, so code
1045 that passed an object duck-typing it would otherwise break at construction; the branch keeps
1046 that code working and nothing more. It is deliberately not advertised as an extension point:
1047 ``CommandsParser`` lives in the private ``redis._parsers`` package, and the supported way to
1048 decide routing yourself is to implement the public ``PolicyResolver`` ABC and pass it as the
1049 ``policy_resolver`` of a cluster client. Policy records also carry no cacheability metadata,
1050 so everything a parser reaching this branch serves reports as non-cacheable.
1051
1052 The async stack needs no counterpart: ``AsyncDynamicMetadataResolver`` takes records rather
1053 than a parser, and ``AsyncDynamicPolicyResolver`` still accepts ``policy_records`` directly.
1054
1055 Raises:
1056 TypeError: If the parser serves neither method.
1057 """
1058 get_metadata = getattr(commands_parser, "get_commands_metadata_cache", None)
1059 if get_metadata is not None:
1060 return get_metadata()
1061
1062 get_policies = getattr(commands_parser, "get_command_policies", None)
1063 if get_policies is None:
1064 raise TypeError(
1065 f"{type(commands_parser).__name__} serves neither get_commands_metadata_cache() nor "
1066 "get_command_policies(); a commands parser must serve one of them"
1067 )
1068
1069 return _build_commands_metadata_cache_from_policies(get_policies())
1070
1071
1072# The records the cluster clients fall back to when the policy resolver does not know a
1073# command, which is the common case: the default resolver is backed by the static table
1074# below, so every write and every read outside it falls through on every execution. Reused
1075# rather than constructed there, both to keep an allocation off that path and because a
1076# frozen record is safe to share.
1077#
1078# Only the routing policies are known for a command the client had to fall back on, so
1079# every other field is recorded at its fail-closed value and none of these reports as
1080# cacheable. Spelled out rather than left to the dataclass defaults, for the reason given
1081# on the shared table shapes below.
1082_DEFAULT_KEYLESS_METADATA = CommandMetadata(
1083 request_policy=RequestPolicy.DEFAULT_KEYLESS,
1084 response_policy=ResponsePolicy.DEFAULT_KEYLESS,
1085 is_readonly=False,
1086 is_blocking=False,
1087 has_key_argument=False,
1088 has_nondeterministic_output=False,
1089 is_script_runner=False,
1090 is_dont_cache=False,
1091 has_complete_metadata=False,
1092)
1093_DEFAULT_KEYED_METADATA = CommandMetadata(
1094 request_policy=RequestPolicy.DEFAULT_KEYED,
1095 response_policy=ResponsePolicy.DEFAULT_KEYED,
1096 is_readonly=False,
1097 is_blocking=False,
1098 has_key_argument=False,
1099 has_nondeterministic_output=False,
1100 is_script_runner=False,
1101 is_dont_cache=False,
1102 has_complete_metadata=False,
1103)
1104
1105# Same, for the node-flag fallback, which resolves a request policy and leaves the response
1106# policy at its keyless default.
1107_METADATA_BY_REQUEST_POLICY: Mapping[RequestPolicy, CommandMetadata] = MappingProxyType(
1108 {
1109 policy: CommandMetadata(
1110 request_policy=policy,
1111 response_policy=ResponsePolicy.DEFAULT_KEYLESS,
1112 is_readonly=False,
1113 is_blocking=False,
1114 has_key_argument=False,
1115 has_nondeterministic_output=False,
1116 is_script_runner=False,
1117 is_dont_cache=False,
1118 has_complete_metadata=False,
1119 )
1120 for policy in RequestPolicy
1121 }
1122)
1123
1124
1125# Every record in this module spells out all nine fields, including the ones that happen to
1126# equal the dataclass default. The nine are not interchangeable: seven of them
1127# (``is_readonly``, ``is_blocking``, ``has_key_argument``, ``has_nondeterministic_output``,
1128# ``is_script_runner``, ``is_dont_cache``, ``has_complete_metadata``) are the inputs to
1129# ``_is_client_side_cacheable``, so a shape that leaves one implicit lets a command added
1130# for an unrelated reason - replica-safe read routing, say, which needs only ``is_readonly``
1131# - become client-side cacheable as a side effect, with nothing in the diff saying so.
1132# Listing every field makes each new entry state its own cacheability.
1133#
1134# Shapes derived with ``dataclasses.replace`` below inherit from a fully explicit base, so
1135# they name only the field that differs and still leave nothing to a default.
1136#
1137# Record shared by every command the client-side cache may serve: readonly, takes a key
1138# name argument, and reports nothing that forbids caching. Spelled out once because the
1139# vast majority of the table below is one of these shapes.
1140#
1141# This includes the ``movablekeys`` commands. Their ``first_key_pos`` is 0, but they do take
1142# keys, so ``has_key_argument`` is True. The cluster client routes them like any other keyed
1143# command: ``determine_slot`` reads their keys from the ``COMMAND`` key specs, and asks the
1144# server with ``COMMAND GETKEYS`` only where a spec is incomplete. The parsers also mark them
1145# keyed, so a live resolver agrees with this record.
1146_CACHEABLE_KEYED = CommandMetadata(
1147 request_policy=RequestPolicy.DEFAULT_KEYED,
1148 response_policy=ResponsePolicy.DEFAULT_KEYED,
1149 is_readonly=True,
1150 is_blocking=False,
1151 has_key_argument=True,
1152 has_nondeterministic_output=False,
1153 is_script_runner=False,
1154 is_dont_cache=False,
1155 has_complete_metadata=True,
1156)
1157
1158# Same, for a read the server tips ``request_policy:multi_shard`` and
1159# ``response_policy:agg_sum``: the cluster client splits its keys by hash slot and sums the
1160# per-slot counts.
1161_CACHEABLE_MULTI_SHARD_SUMMED = replace(
1162 _CACHEABLE_KEYED,
1163 request_policy=RequestPolicy.MULTI_SHARD,
1164 response_policy=ResponsePolicy.AGG_SUM,
1165)
1166
1167# Same, for a command that also carries the ``blocking`` flag, which makes it ineligible:
1168# its reply is what the caller waited for rather than a snapshot the cache may re-serve.
1169# XREAD is the only readonly, keyed command the flag excludes.
1170_BLOCKING_KEYED = replace(_CACHEABLE_KEYED, is_blocking=True)
1171
1172# Same, for the read-only script runners - EVAL_RO, EVALSHA_RO, FCALL_RO. The
1173# ``script_runner`` flag makes them ineligible: the reply is whatever the script computed,
1174# which the client cannot tie to the keys the script happened to touch.
1175#
1176# Recorded rather than left absent because the flag only reaches the client from Redis 8.10
1177# on: on 7.4.x-8.8.x all three report readonly and keyed with no flag that excludes them,
1178# i.e. cacheable, so a resolver reading a live COMMAND reply from one of those servers would
1179# admit them. This record states what the command is, independently of what a given server
1180# version reports. Removable once the minimum CSC-supported server reports ``script_runner``.
1181_SCRIPT_RUNNER_KEYED = replace(_CACHEABLE_KEYED, is_script_runner=True)
1182
1183# Readonly but keyless, so not cacheable: the command observes keyspace state without
1184# taking a key name argument. Note that this is what makes a search or aggregation query
1185# uncacheable - being a module command is not itself a reason to exclude one.
1186_READONLY_KEYLESS = CommandMetadata(
1187 request_policy=RequestPolicy.DEFAULT_KEYLESS,
1188 response_policy=ResponsePolicy.DEFAULT_KEYLESS,
1189 is_readonly=True,
1190 is_blocking=False,
1191 has_key_argument=False,
1192 has_nondeterministic_output=False,
1193 is_script_runner=False,
1194 is_dont_cache=False,
1195 has_complete_metadata=True,
1196)
1197
1198# Readonly and keyless with routing policies withheld, so the cluster client keeps
1199# resolving its target node via COMMAND_FLAGS (e.g. DEFAULT_NODE for DBSIZE/KEYS or
1200# PRIMARIES for SCAN).
1201_READONLY_KEYLESS_WITHHELD_ROUTING = CommandMetadata(
1202 request_policy=None,
1203 response_policy=None,
1204 is_readonly=True,
1205 is_blocking=False,
1206 has_key_argument=False,
1207 has_nondeterministic_output=False,
1208 is_script_runner=False,
1209 is_dont_cache=False,
1210 has_complete_metadata=True,
1211)
1212
1213# Readonly and keyed, but tipped nondeterministic_output, which makes it ineligible
1214# for client-side caching.
1215_NONDETERMINISTIC_KEYED = replace(_CACHEABLE_KEYED, has_nondeterministic_output=True)
1216
1217# Same tip on the keyless reads that withhold their routing. Carries no cacheability
1218# consequence of its own - a keyless command is already ineligible for want of a key
1219# argument - but the table records what the server reports, and SCAN is tipped
1220# ``nondeterministic_output``: it returns an arbitrary page of the keyspace.
1221_NONDETERMINISTIC_KEYLESS_WITHHELD_ROUTING = replace(
1222 _READONLY_KEYLESS_WITHHELD_ROUTING, has_nondeterministic_output=True
1223)
1224
1225# RANDOMKEY, with the server's tips: ``nondeterministic_output``, as it returns an arbitrary
1226# key, and ``request_policy:all_shards`` / ``response_policy:special``. Every primary is
1227# asked, and the cluster client picks a key from the shards that hold one, so the reply is
1228# None only when the whole cluster is empty - which one shard's reply cannot tell.
1229_NONDETERMINISTIC_KEYLESS_ALL_SHARDS_SPECIAL = replace(
1230 _READONLY_KEYLESS,
1231 request_policy=RequestPolicy.ALL_SHARDS,
1232 response_policy=ResponsePolicy.SPECIAL,
1233 has_nondeterministic_output=True,
1234)
1235
1236# Write commands. Rule 1 excludes them, so nothing else about them matters to the cache.
1237_WRITE_KEYLESS = CommandMetadata(
1238 request_policy=RequestPolicy.DEFAULT_KEYLESS,
1239 response_policy=ResponsePolicy.DEFAULT_KEYLESS,
1240 is_readonly=False,
1241 is_blocking=False,
1242 has_key_argument=False,
1243 has_nondeterministic_output=False,
1244 is_script_runner=False,
1245 is_dont_cache=False,
1246 has_complete_metadata=True,
1247)
1248
1249_WRITE_KEYLESS_WITHHELD_ROUTING = CommandMetadata(
1250 request_policy=None,
1251 response_policy=None,
1252 is_readonly=False,
1253 is_blocking=False,
1254 has_key_argument=False,
1255 has_nondeterministic_output=False,
1256 is_script_runner=False,
1257 is_dont_cache=False,
1258 has_complete_metadata=True,
1259)
1260
1261# ``_WRITE_KEYLESS``, for the commands that stop a running script or function - SCRIPT KILL
1262# and FUNCTION KILL. The server tips them ``request_policy:all_shards`` and
1263# ``response_policy:one_succeeded``: only the shard running the script can stop it, so every
1264# primary is asked, the NOTBUSY errors of the others are dropped, and the one success is the
1265# reply. The server flags them neither ``readonly`` nor ``write``, so ``is_readonly`` is False.
1266_KILL_KEYLESS_ONE_SUCCEEDED = replace(
1267 _WRITE_KEYLESS,
1268 request_policy=RequestPolicy.ALL_SHARDS,
1269 response_policy=ResponsePolicy.ONE_SUCCEEDED,
1270)
1271
1272# ``_WRITE_KEYLESS``, for the diagnostics commands each node answers about itself -
1273# FUNCTION STATS, MEMORY DOCTOR and the LATENCY reports. The server tips them
1274# ``nondeterministic_output`` and ``response_policy:special`` with no merge it could name, so
1275# the cluster client keeps their replies keyed by node. FUNCTION STATS and MEMORY DOCTOR are
1276# tipped ``request_policy:all_shards``, the LATENCY reports ``all_nodes``, as a replica
1277# keeps latency samples of its own. None is flagged ``readonly``.
1278_NONDETERMINISTIC_KEYLESS_PER_SHARD = replace(
1279 _WRITE_KEYLESS,
1280 request_policy=RequestPolicy.ALL_SHARDS,
1281 response_policy=ResponsePolicy.SPECIAL,
1282 has_nondeterministic_output=True,
1283)
1284_NONDETERMINISTIC_KEYLESS_PER_NODE = replace(
1285 _NONDETERMINISTIC_KEYLESS_PER_SHARD, request_policy=RequestPolicy.ALL_NODES
1286)
1287
1288_WRITE_KEYED = CommandMetadata(
1289 request_policy=RequestPolicy.DEFAULT_KEYED,
1290 response_policy=ResponsePolicy.DEFAULT_KEYED,
1291 is_readonly=False,
1292 is_blocking=False,
1293 has_key_argument=True,
1294 has_nondeterministic_output=False,
1295 is_script_runner=False,
1296 is_dont_cache=False,
1297 has_complete_metadata=True,
1298)
1299
1300# The same three shapes for the commands the server tips ``dont_cache``. The search module
1301# tips nearly its whole surface that way, including the write commands, where the marker is
1302# redundant - rule 1 already excludes them. It is recorded anyway so the table keeps
1303# reporting what the server reports.
1304_DONT_CACHE_READONLY_KEYLESS = replace(_READONLY_KEYLESS, is_dont_cache=True)
1305_DONT_CACHE_WRITE_KEYLESS = replace(_WRITE_KEYLESS, is_dont_cache=True)
1306_DONT_CACHE_WRITE_KEYED = replace(_WRITE_KEYED, is_dont_cache=True)
1307
1308
1309# =============================================================================
1310# Static command metadata table
1311# =============================================================================
1312# This table is seeded from old ``CacheConfig.DEFAULT_ALLOW_LIST`` and ``redis.commands.policies.STATIC_POLICIES``.
1313#
1314# Every entry below was validated against a live ``COMMAND`` reply from Redis 8.10.0 with
1315# search, timeseries, ReJSON, bf and vectorset loaded (the ``redislabs/client-libs-test``
1316# stack image), with the core entries also compared against 7.4.2 to ensure the minimum
1317# supported version does not disagree on the fields that decide cacheability. The
1318# exceptions are the ``bless`` container, which first ships in 8.11 and was validated against
1319# that release's ``COMMAND INFO`` reply, and the set member expiration reads (``sexpiretime``,
1320# ``spexpiretime``, ``sttl``, ``spttl``) and ``bitrangeintarray``, which first ship in 8.12
1321# and were validated against the ``COMMAND INFO`` reply of an 8.11.240 build.
1322#
1323# The table is not exhaustive: on 8.10.0 the server reports 127 cacheable commands and this
1324# covers 80 of them. The count is version-qualified because it moves between releases - a
1325# later server reports more. The uncovered ones are whole module surfaces the CSC allow-list
1326# never carried - ``bf.*``, ``cf.*``, ``cms.*``, ``topk.*``, ``tdigest.*``, the vectorset
1327# reads - plus core reads such as ``pfcount``. A command absent from the table fails closed,
1328# so the uncovered commands are simply treated as not cacheable.
1329#
1330# Every command on the default allow-list of the 7.1.0 client-side cache is present.
1331# So are all of their module counterparts, plus a selection of write commands.
1332# Write commands carry the metadata that makes them *ineligible*, so the reason
1333# is documented in one place rather than inferred from an absence - and, because
1334# a resolver answers from the first record it finds, so that a live resolver
1335# chained behind this one cannot re-admit them. ``xpending``, ``ts.info`` and
1336# ``xread`` are on today's ``CacheConfig.DEFAULT_ALLOW_LIST``, and the server
1337# confirms all three are defects in that list: ``xpending`` is tipped
1338# ``nondeterministic_output``, ``ts.info`` ``dont_cache``, and ``xread`` carries
1339# the ``blocking`` command flag.
1340#
1341# Four entries diverge from the live reply, each for a reason spelled out where it occurs:
1342# ``mget`` stands in the keyed defaults for its ``multi_shard`` tip, ``ft.cursor`` is SPECIAL,
1343# a client-side decision the server does not tip, ``touch`` is recorded ``dont_cache`` where
1344# the server reports it cacheable, and ``vrandmember`` is recorded ``nondeterministic_output``
1345# where the server tips it nothing. ``bless scan``, ``command``, ``dbsize``, ``keys``,
1346# ``scan`` and ``vrandmember`` withhold their routing policies entirely, so the cluster
1347# client keeps resolving their targets itself. Their cacheability inputs are unaffected.
1348# DBSIZE and KEYS are tipped ``request_policy:all_shards``, but recording that would change
1349# what they answer on a cluster - every primary instead of the default node - so the
1350# COMMAND_FLAGS routing stands. ``randomkey`` records its tips: the answer it gains is the
1351# one the command promises, a key from anywhere in the keyspace.
1352#
1353# The ``movablekeys`` reads - ``eval_ro``, ``evalsha_ro``, ``fcall_ro``, ``sdiffcard``,
1354# ``sintercard``, ``sunioncard``, ``xread``, ``zdiff``, ``zinter``, ``zintercard`` and
1355# ``zunion`` - record the keyed defaults the parsers derive from their key specs, so none of
1356# them diverges.
1357_STATIC_COMMAND_METADATA: CommandMetadataRecordsCache = MappingProxyType(
1358 {
1359 "core": MappingProxyType(
1360 {
1361 # The BACKUP container, keyed by subcommand. Keyless admin commands that the
1362 # server flags neither ``readonly`` nor ``write`` and tips nothing. Routing
1363 # policies are withheld because the cluster client sends them to the default
1364 # node through their COMMAND_FLAGS entry, as it does SAVE and LASTSAVE: a
1365 # backup belongs to one node, so a caller picks others with ``target_nodes``.
1366 "backup abort": _WRITE_KEYLESS_WITHHELD_ROUTING,
1367 "backup cleanup": _WRITE_KEYLESS_WITHHELD_ROUTING,
1368 "backup list": _WRITE_KEYLESS_WITHHELD_ROUTING,
1369 "backup seal": _WRITE_KEYLESS_WITHHELD_ROUTING,
1370 "backup start": _WRITE_KEYLESS_WITHHELD_ROUTING,
1371 "backup status": _WRITE_KEYLESS_WITHHELD_ROUTING,
1372 "bitcount": _CACHEABLE_KEYED,
1373 "bitfield_ro": _CACHEABLE_KEYED,
1374 "bitpos": _CACHEABLE_KEYED,
1375 "bitrangeintarray": _CACHEABLE_KEYED,
1376 # The BLESS container, keyed by subcommand the way ``execute_command``
1377 # receives it. Validated against the 8.11 ``COMMAND INFO`` reply, the first
1378 # release that reports it.
1379 "bless clear": _WRITE_KEYED,
1380 # Not cacheable and not replica-eligible: the server flags BLESS GET ``fast``
1381 # only - neither ``readonly`` nor ``write`` - and ``is_readonly`` records the
1382 # command flag, not the ``RO`` key spec, so it fails closed on both counts.
1383 # Recorded with the write shape for the same reason ``command`` is below.
1384 "bless get": _WRITE_KEYED,
1385 # Keyless, tipped nondeterministic_output and request_policy:special /
1386 # response_policy:special, exactly like SCAN. Routing policies are withheld
1387 # for the same reason as SCAN: the cluster client routes BLESS SCAN to all
1388 # primary nodes (PRIMARIES) through its COMMAND_FLAGS entry and merges the
1389 # per-node cursors. Unlike SCAN the server reports no flags at all, so it is
1390 # not readonly.
1391 "bless scan": CommandMetadata(
1392 request_policy=None,
1393 response_policy=None,
1394 is_readonly=False,
1395 is_blocking=False,
1396 has_key_argument=False,
1397 has_nondeterministic_output=True,
1398 is_script_runner=False,
1399 is_dont_cache=False,
1400 has_complete_metadata=True,
1401 ),
1402 "bless set": _WRITE_KEYED,
1403 # From STATIC_POLICIES. COMMAND is flagged loading/stale, not readonly,
1404 # and takes no keys. Routing policies are withheld so the cluster client preserves
1405 # the 2-word COMMAND COUNT, COMMAND LIST, COMMAND GETKEYS default-node flags.
1406 "command": _WRITE_KEYLESS_WITHHELD_ROUTING,
1407 "dbsize": _READONLY_KEYLESS_WITHHELD_ROUTING,
1408 "digest": _CACHEABLE_KEYED,
1409 "dump": _NONDETERMINISTIC_KEYED,
1410 # Not cacheable: script_runner. See the shape's note for why all three are
1411 # recorded rather than left to the server to report.
1412 "eval_ro": _SCRIPT_RUNNER_KEYED,
1413 "evalsha_ro": _SCRIPT_RUNNER_KEYED,
1414 # Tipped request_policy:multi_shard / response_policy:agg_sum: the cluster
1415 # client splits the keys by hash slot and sums the counts. Keys that share a
1416 # slot are sent as one command, exactly as the keyed defaults sent them.
1417 "exists": _CACHEABLE_MULTI_SHARD_SUMMED,
1418 "expiretime": _CACHEABLE_KEYED,
1419 "fcall_ro": _SCRIPT_RUNNER_KEYED,
1420 "function kill": _KILL_KEYLESS_ONE_SUCCEEDED,
1421 "function stats": _NONDETERMINISTIC_KEYLESS_PER_SHARD,
1422 "geodist": _CACHEABLE_KEYED,
1423 "geohash": _CACHEABLE_KEYED,
1424 "geopos": _CACHEABLE_KEYED,
1425 "georadius_ro": _CACHEABLE_KEYED,
1426 "georadiusbymember_ro": _CACHEABLE_KEYED,
1427 "geosearch": _CACHEABLE_KEYED,
1428 "get": _CACHEABLE_KEYED,
1429 "getbit": _CACHEABLE_KEYED,
1430 "getrange": _CACHEABLE_KEYED,
1431 "hexists": _CACHEABLE_KEYED,
1432 "hexpiretime": _CACHEABLE_KEYED,
1433 "hget": _CACHEABLE_KEYED,
1434 # HGETALL, HKEYS, HVALS, SDIFF, SINTER, SMEMBERS and SUNION all carry
1435 # nondeterministic_output_order, which is a different tip from
1436 # nondeterministic_output and does not prevent caching. Matching tips by
1437 # prefix would silently drop all seven.
1438 "hgetall": _CACHEABLE_KEYED,
1439 "hkeys": _CACHEABLE_KEYED,
1440 "hlen": _CACHEABLE_KEYED,
1441 "hmget": _CACHEABLE_KEYED,
1442 "hpexpiretime": _CACHEABLE_KEYED,
1443 "hpttl": _NONDETERMINISTIC_KEYED,
1444 "hrandfield": _NONDETERMINISTIC_KEYED,
1445 "hscan": _NONDETERMINISTIC_KEYED,
1446 "hstrlen": _CACHEABLE_KEYED,
1447 "httl": _NONDETERMINISTIC_KEYED,
1448 "hvals": _CACHEABLE_KEYED,
1449 "keys": _READONLY_KEYLESS_WITHHELD_ROUTING,
1450 "latency doctor": _NONDETERMINISTIC_KEYLESS_PER_NODE,
1451 "latency graph": _NONDETERMINISTIC_KEYLESS_PER_NODE,
1452 "latency histogram": _NONDETERMINISTIC_KEYLESS_PER_NODE,
1453 "lcs": _CACHEABLE_KEYED,
1454 "lindex": _CACHEABLE_KEYED,
1455 "llen": _CACHEABLE_KEYED,
1456 "lpos": _CACHEABLE_KEYED,
1457 "lrange": _CACHEABLE_KEYED,
1458 "memory doctor": _NONDETERMINISTIC_KEYLESS_PER_SHARD,
1459 # Tipped request_policy:multi_shard by the server, but recorded keyed on
1460 # purpose: ``mget`` documents that keys in different hash slots raise
1461 # ``RedisClusterException`` on a cluster, and splitting them instead would
1462 # make the read silently non-atomic. ``mget_nonatomic`` is the opt-in split.
1463 "mget": _CACHEABLE_KEYED,
1464 "pexpiretime": _CACHEABLE_KEYED,
1465 "pttl": _NONDETERMINISTIC_KEYED,
1466 "randomkey": _NONDETERMINISTIC_KEYLESS_ALL_SHARDS_SPECIAL,
1467 # Readonly and keyless. Routing policies are withheld so the cluster client keeps
1468 # routing SCAN to all primary nodes (PRIMARIES) rather than a single random node.
1469 "scan": _NONDETERMINISTIC_KEYLESS_WITHHELD_ROUTING,
1470 "scard": _CACHEABLE_KEYED,
1471 "script kill": _KILL_KEYLESS_ONE_SUCCEEDED,
1472 "sdiff": _CACHEABLE_KEYED,
1473 "sdiffcard": _CACHEABLE_KEYED,
1474 "sexpiretime": _CACHEABLE_KEYED,
1475 "sinter": _CACHEABLE_KEYED,
1476 "sintercard": _CACHEABLE_KEYED,
1477 "sismember": _CACHEABLE_KEYED,
1478 "smembers": _CACHEABLE_KEYED,
1479 "smismember": _CACHEABLE_KEYED,
1480 # Unreachable today: ``CoreCommands.sort_ro`` delegates to ``sort()``, which
1481 # sends SORT rather than SORT_RO, so nothing resolves this entry. Recorded
1482 # because SORT_RO is genuinely cacheable, and the old allow-list carried it
1483 # just as ineffectively.
1484 # TODO: drop this note once the command method sends its own name.
1485 "sort_ro": _CACHEABLE_KEYED,
1486 "spexpiretime": _CACHEABLE_KEYED,
1487 "spttl": _NONDETERMINISTIC_KEYED,
1488 "srandmember": _NONDETERMINISTIC_KEYED,
1489 "sscan": _NONDETERMINISTIC_KEYED,
1490 "strlen": _CACHEABLE_KEYED,
1491 "sttl": _NONDETERMINISTIC_KEYED,
1492 "substr": _CACHEABLE_KEYED,
1493 "sunion": _CACHEABLE_KEYED,
1494 "sunioncard": _CACHEABLE_KEYED,
1495 # Not cacheable, and the one entry in this table that records a client-side
1496 # judgement instead of what the server reports: TOUCH has a server-side
1497 # effect - it refreshes each key's idle time, which is what LRU/LFU
1498 # eviction and OBJECT IDLETIME read - so it must reach the server on every
1499 # call. No server flag or tip expresses that; measured on 8.10.0 the server
1500 # reports it readonly and keyed with no ``dont_cache`` tip, i.e. cacheable.
1501 # Recorded here as ``dont_cache`` so the reason is stated once rather than
1502 # left to every resolver in a chain. Removable once the server tips it
1503 # ``dont_cache``.
1504 #
1505 # Routed like EXISTS: the server tips TOUCH request_policy:multi_shard /
1506 # response_policy:agg_sum, so its keys are split by hash slot and the counts
1507 # summed.
1508 "touch": CommandMetadata(
1509 request_policy=RequestPolicy.MULTI_SHARD,
1510 response_policy=ResponsePolicy.AGG_SUM,
1511 is_readonly=True,
1512 is_blocking=False,
1513 has_key_argument=True,
1514 has_nondeterministic_output=False,
1515 is_script_runner=False,
1516 is_dont_cache=True,
1517 has_complete_metadata=True,
1518 ),
1519 "ttl": _NONDETERMINISTIC_KEYED,
1520 "type": _CACHEABLE_KEYED,
1521 # Not cacheable: its reply is a random sample of the vector set, so re-serving
1522 # it from a cache would stop it varying. Every core random read - SRANDMEMBER,
1523 # ZRANDMEMBER, HRANDFIELD, RANDOMKEY - is tipped ``nondeterministic_output``
1524 # by the server; measured on 8.10.0 VRANDMEMBER reports no tips at all, so the
1525 # algorithm would admit it. Recorded as nondeterministic because that is what
1526 # it is, and it is the one other command node-redis hard-codes ineligible
1527 # besides TOUCH. Removable once the server tips it like its core siblings.
1528 #
1529 # Routing policies are withheld for the same reason as ``touch`` above: the
1530 # record exists for its cacheability inputs, and must not start routing a
1531 # command the cluster client resolves for itself today.
1532 "vrandmember": CommandMetadata(
1533 request_policy=None,
1534 response_policy=None,
1535 is_readonly=True,
1536 is_blocking=False,
1537 has_key_argument=True,
1538 has_nondeterministic_output=True,
1539 is_script_runner=False,
1540 is_dont_cache=False,
1541 has_complete_metadata=True,
1542 ),
1543 "xlen": _CACHEABLE_KEYED,
1544 # Not cacheable: nondeterministic_output. It is on today's allow-list,
1545 # which is a defect in that list rather than a reason to keep caching it.
1546 "xpending": _NONDETERMINISTIC_KEYED,
1547 "xrange": _CACHEABLE_KEYED,
1548 "xread": _BLOCKING_KEYED,
1549 "xrevrange": _CACHEABLE_KEYED,
1550 "zcard": _CACHEABLE_KEYED,
1551 "zcount": _CACHEABLE_KEYED,
1552 "zdiff": _CACHEABLE_KEYED,
1553 "zinter": _CACHEABLE_KEYED,
1554 "zintercard": _CACHEABLE_KEYED,
1555 "zlexcount": _CACHEABLE_KEYED,
1556 "zmscore": _CACHEABLE_KEYED,
1557 "zrange": _CACHEABLE_KEYED,
1558 "zrangebylex": _CACHEABLE_KEYED,
1559 "zrangebyscore": _CACHEABLE_KEYED,
1560 "zrank": _CACHEABLE_KEYED,
1561 "zrandmember": _NONDETERMINISTIC_KEYED,
1562 "zrevrange": _CACHEABLE_KEYED,
1563 "zrevrangebylex": _CACHEABLE_KEYED,
1564 "zrevrangebyscore": _CACHEABLE_KEYED,
1565 "zrevrank": _CACHEABLE_KEYED,
1566 "zscan": _NONDETERMINISTIC_KEYED,
1567 "zscore": _CACHEABLE_KEYED,
1568 "zunion": _CACHEABLE_KEYED,
1569 }
1570 ),
1571 "json": MappingProxyType(
1572 {
1573 "arrindex": _CACHEABLE_KEYED,
1574 "arrlen": _CACHEABLE_KEYED,
1575 "get": _CACHEABLE_KEYED,
1576 "mget": _CACHEABLE_KEYED,
1577 "objkeys": _CACHEABLE_KEYED,
1578 "objlen": _CACHEABLE_KEYED,
1579 "resp": _CACHEABLE_KEYED,
1580 "strlen": _CACHEABLE_KEYED,
1581 "type": _CACHEABLE_KEYED,
1582 }
1583 ),
1584 "ts": MappingProxyType(
1585 {
1586 "get": _CACHEABLE_KEYED,
1587 # Not cacheable: the server reports dont_cache for TS.INFO, contradicting
1588 # today's allow-list, which caches it.
1589 "info": CommandMetadata(
1590 request_policy=RequestPolicy.DEFAULT_KEYED,
1591 response_policy=ResponsePolicy.DEFAULT_KEYED,
1592 is_readonly=True,
1593 is_blocking=False,
1594 has_key_argument=True,
1595 has_nondeterministic_output=False,
1596 is_script_runner=False,
1597 is_dont_cache=True,
1598 has_complete_metadata=True,
1599 ),
1600 "range": _CACHEABLE_KEYED,
1601 "revrange": _CACHEABLE_KEYED,
1602 }
1603 ),
1604 # From STATIC_POLICIES. Only the suggestion-dictionary commands take a key name
1605 # argument, so FT.SUGGET and FT.SUGLEN are the only cacheable entries here -
1606 # FT.SEARCH and FT.AGGREGATE are readonly but keyless.
1607 #
1608 # The search module tips almost its whole surface ``dont_cache``. The exceptions
1609 # are FT.CURSOR, FT.DROP, FT.SUGGET and FT.SUGLEN, which report no tips at all -
1610 # which is what keeps the two suggestion-dictionary reads cacheable.
1611 "ft": MappingProxyType(
1612 {
1613 "aggregate": _DONT_CACHE_READONLY_KEYLESS,
1614 "aliasadd": _DONT_CACHE_WRITE_KEYLESS,
1615 "aliasdel": _DONT_CACHE_WRITE_KEYLESS,
1616 "aliaslist": _DONT_CACHE_READONLY_KEYLESS,
1617 "aliasupdate": _DONT_CACHE_WRITE_KEYLESS,
1618 "alter": _DONT_CACHE_WRITE_KEYLESS,
1619 "create": _DONT_CACHE_WRITE_KEYLESS,
1620 # SPECIAL is a client-side routing decision, not a server tip: FT.CURSOR
1621 # must reach the node that ran the FT.AGGREGATE it continues, which
1622 # ``get_special_nodes`` resolves. The server reports no tips for it, so a
1623 # generated table would say DEFAULT_KEYLESS and break cursor routing.
1624 "cursor": CommandMetadata(
1625 request_policy=RequestPolicy.SPECIAL,
1626 response_policy=ResponsePolicy.DEFAULT_KEYLESS,
1627 is_readonly=True,
1628 is_blocking=False,
1629 has_key_argument=False,
1630 has_nondeterministic_output=False,
1631 is_script_runner=False,
1632 is_dont_cache=False,
1633 has_complete_metadata=True,
1634 ),
1635 "dictadd": _DONT_CACHE_WRITE_KEYLESS,
1636 "dictdel": _DONT_CACHE_WRITE_KEYLESS,
1637 "dictdump": _DONT_CACHE_READONLY_KEYLESS,
1638 "drop": _WRITE_KEYLESS,
1639 "dropindex": _DONT_CACHE_WRITE_KEYLESS,
1640 "explain": _DONT_CACHE_READONLY_KEYLESS,
1641 "explaincli": _DONT_CACHE_READONLY_KEYLESS,
1642 "info": _DONT_CACHE_READONLY_KEYLESS,
1643 "profile": _DONT_CACHE_READONLY_KEYLESS,
1644 "search": _DONT_CACHE_READONLY_KEYLESS,
1645 "spellcheck": _DONT_CACHE_READONLY_KEYLESS,
1646 "sugadd": _DONT_CACHE_WRITE_KEYED,
1647 "sugdel": _DONT_CACHE_WRITE_KEYED,
1648 "sugget": _CACHEABLE_KEYED,
1649 "suglen": _CACHEABLE_KEYED,
1650 "syndump": _DONT_CACHE_READONLY_KEYLESS,
1651 "synupdate": _DONT_CACHE_WRITE_KEYLESS,
1652 "tagvals": _DONT_CACHE_READONLY_KEYLESS,
1653 }
1654 ),
1655 }
1656)