Skip to content

glide_sync.glide_client

RdmaReadReceipt dataclass

What the server reported about a completed read.

Attributes:

Name Type Description
bytes_written int

Bytes the server moved into the window.

checksum Optional[int]

CRC-32c the server computed over those bytes. The landed bytes have already been verified against it.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
129
130
131
132
133
134
135
136
137
138
139
140
141
@dataclass(frozen=True)
class RdmaReadReceipt:
    """
    What the server reported about a completed read.

    Attributes:
        bytes_written (int): Bytes the server moved into the window.
        checksum (Optional[int]): CRC-32c the server computed over those bytes.
            The landed bytes have already been verified against it.
    """

    bytes_written: int
    checksum: Optional[int] = None

RdmaWindow dataclass

The span of a registered region one transfer uses.

Attributes:

Name Type Description
region RdmaRegion

The region the window belongs to.

offset int

Where the window starts within the region.

length int

How many bytes it covers.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
@dataclass(frozen=True)
class RdmaWindow:
    """
    The span of a registered region one transfer uses.

    Attributes:
        region (RdmaRegion): The region the window belongs to.
        offset (int): Where the window starts within the region.
        length (int): How many bytes it covers.
    """

    region: "RdmaRegion"
    offset: int
    length: int

    def memoryview(self) -> memoryview:
        """
        A view of just this window for reading what a transfer landed or
        staging what one will send.

        Raises:
            RdmaError: If the region has been closed.
        """
        return self.region.memoryview()[self.offset : self.offset + self.length]

memoryview()

A view of just this window for reading what a transfer landed or staging what one will send.

Raises:

Type Description
RdmaError

If the region has been closed.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
159
160
161
162
163
164
165
166
167
def memoryview(self) -> memoryview:
    """
    A view of just this window for reading what a transfer landed or
    staging what one will send.

    Raises:
        RdmaError: If the region has been closed.
    """
    return self.region.memoryview()[self.offset : self.offset + self.length]

RdmaRegion

Memory registered with the server for RDMA transfers.

The memory is the caller's: this holds a reference to it and registers it with the client's fabric, but never copies or owns it. Register one large region at start-up and address windows of it per transfer rather than registering per operation.

The pages stay pinned until :meth:close is called, and the buffer must not be resized or freed before then. The server writes into it at times the caller does not control, so a transfer must not overlap any other use of the same window.

Only one transfer may use a region at a time, even when each transfer uses a different window. Threads that transfer concurrently each need their own region, for example one per non-overlapping slice of the same buffer. A transfer that finds the region already in use by another raises RdmaError, and so does :meth:close while a transfer is using it.

Create one with :meth:BaseClient.register_rdma_region. Close it with :meth:close, or use it as a context manager. A region garbage-collected without being closed is freed then, with a ResourceWarning; until then its pages stay pinned::

with client.register_rdma_region(bytearray(1 << 20)) as region:
    client.rdma_set(b"key", region.window(0, 4096))

Handling a failed transfer: some failures leave the region usable, such as a value too large for its window, a checksum mismatch, or a refusal from the server. Others close it, because the server might still be using the memory:

  • the connection was lost while the transfer was in flight;
  • the client was closed to cancel the transfer;
  • the server's reply was neither a result nor an error, such as the +QUEUED a server sends when another thread has a MULTI open on this client, which means the server may still run the transfer on EXEC.

The error's class does not say which happened. For example, a handshake that leaves the connection unusable raises ConnectionError but keeps the region open, since the transfer was never sent, and the client reconnects for the next one. So check :attr:closed after any error, and register the memory again if the client is still open::

try:
    receipt = client.rdma_get(key, region.window(offset, length))
except GlideError:
    if region.closed and not client.closed:
        region = client.register_rdma_region(slab)
    raise

Whether to retry is left to the caller, since only the caller knows whether sending a value again is safe. On efa-direct the same memory can be registered again at once. GLIDE refuses it, raising RdmaError, only while it still holds the memory: on the tcp provider, which is for development only, or after a failed deregistration. See :attr:memory_released.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
class RdmaRegion:
    """
    Memory registered with the server for RDMA transfers.

    The memory is the caller's: this holds a reference to it and registers it
    with the client's fabric, but never copies or owns it. Register one
    large region at start-up and address windows of it per transfer rather than
    registering per operation.

    The pages stay pinned until :meth:`close` is called, and the buffer must not
    be resized or freed before then. The server writes into it at times the
    caller does not control, so a transfer must not overlap any other use of the
    same window.

    Only one transfer may use a region at a time, even when each transfer uses
    a different window. Threads that transfer concurrently each need their own
    region, for example one per non-overlapping slice of the same buffer. A
    transfer that finds the region already in use by another raises
    ``RdmaError``, and so does :meth:`close` while a transfer is using it.

    Create one with :meth:`BaseClient.register_rdma_region`. Close it with
    :meth:`close`, or use it as a context manager. A region garbage-collected
    without being closed is freed then, with a ``ResourceWarning``; until
    then its pages stay pinned::

        with client.register_rdma_region(bytearray(1 << 20)) as region:
            client.rdma_set(b"key", region.window(0, 4096))

    Handling a failed transfer: some failures leave the region usable, such as
    a value too large for its window, a checksum mismatch, or a refusal from
    the server. Others close it, because the server might still be using the
    memory:

    - the connection was lost while the transfer was in flight;
    - the client was closed to cancel the transfer;
    - the server's reply was neither a result nor an error, such as the
      ``+QUEUED`` a server sends when another thread has a ``MULTI`` open on
      this client, which means the server may still run the transfer on
      ``EXEC``.

    The error's class does not say which happened. For example, a handshake
    that leaves the connection unusable raises ``ConnectionError`` but keeps
    the region open, since the transfer was never sent, and the client
    reconnects for the next one. So check :attr:`closed` after any error, and
    register the memory again if the client is still open::

        try:
            receipt = client.rdma_get(key, region.window(offset, length))
        except GlideError:
            if region.closed and not client.closed:
                region = client.register_rdma_region(slab)
            raise

    Whether to retry is left to the caller, since only the caller knows whether
    sending a value again is safe. On efa-direct the same memory can be
    registered again at once. GLIDE refuses it, raising ``RdmaError``, only
    while it still holds the memory: on the tcp provider, which is for
    development only, or after a failed deregistration. See
    :attr:`memory_released`.
    """

    def __init__(self, client: "BaseClient", memory: Any, region):
        # Both references keep the caller's allocation alive for as long as the
        # server may write to it: the object itself, and the cdata view CFFI
        # made of it.
        self._memory = memory
        self._view = client._ffi.from_buffer(memory)
        try:
            self._span = _memory_span(memory)
            self._client = client
            self._region = region
            # The FFI registers exactly the bytes it is handed, so the region
            # holds as many bytes as the memory spans.
            self._capacity = self._span[1] - self._span[0]
            # Set by `close` when the fabric still kept the memory.
            self._hold = None
            # Guards `_region` and `_busy`. Held only briefly, never for the
            # length of a transfer, so closing the client can still cancel one.
            self._lock = threading.Lock()
            # Whether a transfer is using the region. The FFI frees the region
            # in `free_rdma_region` and takes it exclusively for each transfer,
            # so a second transfer or a close while this is set would corrupt
            # memory.
            self._busy = False
            # Frees the region if this object is collected without `close`. Its
            # arguments keep the caller's memory alive until then, so the memory
            # is never freed while still registered. A transfer in flight keeps
            # this object reachable, so the finalizer never runs under one.
            # Skipped at interpreter exit, when the library may already be gone
            # and the process's teardown releases the memory anyway.
            #
            # Keep this the last step that can fail. If construction raises
            # before it, `register_rdma_region` frees the region, and a
            # finalizer already attached would free it a second time.
            self._finalizer = weakref.finalize(
                self,
                _finalize_rdma_region,
                client._lib,
                client._ffi,
                region,
                memory,
                self._view,
                self._span,
            )
            # A documented writable property that typeshed's stub leaves out.
            self._finalizer.atexit = False  # type: ignore[misc]
        except BaseException:
            # The error's traceback keeps `_view` alive, through this half-built
            # region and through the arguments of whatever call failed. If
            # `memory` is a memoryview and the error ends up in a reference
            # cycle, Python 3.9's garbage collector crashes freeing it while
            # `_view` still holds an export on it. Releasing ends the export
            # however many references remain. `register_rdma_region` keeps its
            # own export if the fabric still holds the memory, so this one is
            # not needed for that.
            client._ffi.release(self._view)
            raise

    @property
    def capacity(self) -> int:
        """How many bytes were registered."""
        return self._capacity

    @property
    def closed(self) -> bool:
        """
        Whether the region has been deregistered, by :meth:`close` or by a
        transfer that ended before the server was known to be done with the
        memory; see :class:`RdmaRegion`.
        """
        return self._region is None

    @property
    def memory_released(self) -> bool:
        """
        Whether the caller may reuse or free the registered memory.

        False while the region is open. After it closes, False while GLIDE
        still holds the memory because a write could still land in it: after
        a transfer closed the region on the tcp provider, until the client and
        all its regions are closed, or after a failed deregistration, for good.
        True otherwise, which on efa-direct is as soon as the region closes.

        Registering memory GLIDE still holds is refused, so a caller who only
        wants to register the same memory again can try that and handle the
        error rather than check this first.

        Example:
            >>> region.close()
            >>> if not region.memory_released:
            ...     slab = bytearray(len(slab))  # the old one may still be written
        """
        if not self.closed:
            return False
        return self._hold is None or _RETAINED_RDMA_MEMORY.released(self._hold)

    def window(self, offset: int = 0, length: Optional[int] = None) -> RdmaWindow:
        """
        The span of this region a transfer should use.

        Args:
            offset (int): Where the window starts. Defaults to 0.
            length (Optional[int]): How many bytes it covers. If not set, the
                rest of the region from ``offset``.

        Returns:
            RdmaWindow: The window, to pass to ``rdma_get`` or ``rdma_set``.

        Raises:
            RdmaError: If the region is closed or the window runs outside it.

        Example:
            >>> region.window()            # the whole region
            >>> region.window(4096, 1024)  # 1 KiB starting 4 KiB in
        """
        self._require_open()

        if offset < 0:
            raise RdmaError(f"offset must not be negative, got {offset}")
        if offset > self._capacity:
            raise RdmaError(
                f"offset {offset} is past the end of a region of "
                f"{self._capacity} bytes"
            )

        if length is None:
            length = self._capacity - offset
        elif length < 0:
            raise RdmaError(f"length must not be negative, got {length}")
        elif offset + length > self._capacity:
            raise RdmaError(
                f"window [{offset}, {offset + length}) runs past the end of a "
                f"region of {self._capacity} bytes"
            )

        return RdmaWindow(self, offset, length)

    def memoryview(self) -> memoryview:
        """
        A view of the registered memory as a span of bytes.

        Raises:
            RdmaError: If the region has been closed.
        """
        self._require_open()
        return memoryview(self._memory).cast("B")

    def close(self) -> None:
        """
        Deregister the memory and release the pinned pages.

        The caller's buffer is not freed. Usually it can be reused or freed once
        this returns. The exception is a region a transfer closed on the tcp
        provider, or whose deregistration failed: a write may still land in it,
        so GLIDE keeps the buffer referenced until the fabric is done with it,
        and the caller should not reuse it either. On tcp that is once the
        client and all its regions are closed; after a failed deregistration,
        which is logged as an error, it is never. :attr:`memory_released` says
        which. Closing twice is a no-op, so this is safe in a ``finally``.

        This is not a way to cancel a transfer. To cancel one in flight, close
        the client from another thread: the transfer then closes its region on
        the way out, so closing it again is a no-op.

        Raises:
            RdmaError: If a transfer is using the region. Closing it then would
                free the region under the transfer.
        """
        with self._lock:
            if self._busy:
                raise RdmaError(
                    "this RDMA region is in use by a transfer, so it cannot be "
                    "closed yet; close the client to cancel the transfer, which "
                    "then closes the region itself"
                )
            self._close_locked()

    def _close_locked(self) -> None:
        """:meth:`close`, with `_lock` held and no transfer using the region."""
        self._region = None
        # `detach` hands back the finalizer's arguments only the first time,
        # so the region is freed exactly once, by this or by the finalizer.
        detached = self._finalizer.detach()
        if detached is not None:
            _, _, arguments, _ = detached
            self._hold = _free_rdma_region(*arguments)
        else:
            _RETAINED_RDMA_MEMORY.release_what_is_free()
        self._view = None
        self._memory = None

    def _require_open(self):
        """The region pointer, or an error naming what went wrong."""
        if self._region is None:
            raise RdmaError("this RDMA region is closed")
        return self._region

    def _begin_transfer(self):
        """
        Mark the region in use by a transfer and return its pointer. Every call
        must be paired with :meth:`_end_transfer`.
        """
        with self._lock:
            if self._busy:
                raise RdmaError(
                    "this RDMA region is in use by another transfer; only one "
                    "transfer may use a region at a time"
                )
            region = self._require_open()
            self._busy = True
            return region

    def _end_transfer(self, close: bool) -> None:
        """
        Mark the transfer done, first closing the region if the transfer left
        it unusable, so no other call can use the region in between.
        """
        with self._lock:
            self._busy = False
            if close:
                self._close_locked()

    def __enter__(self) -> "RdmaRegion":
        return self

    def __exit__(
        self,
        exc_type: Optional[type[BaseException]],
        exc: Optional[BaseException],
        tb: Optional[TracebackType],
    ) -> None:
        self.close()

    def __repr__(self) -> str:
        state = "closed" if self.closed else f"{self._capacity} bytes"
        return f"RdmaRegion({state})"

capacity property

How many bytes were registered.

closed property

Whether the region has been deregistered, by :meth:close or by a transfer that ended before the server was known to be done with the memory; see :class:RdmaRegion.

memory_released property

Whether the caller may reuse or free the registered memory.

False while the region is open. After it closes, False while GLIDE still holds the memory because a write could still land in it: after a transfer closed the region on the tcp provider, until the client and all its regions are closed, or after a failed deregistration, for good. True otherwise, which on efa-direct is as soon as the region closes.

Registering memory GLIDE still holds is refused, so a caller who only wants to register the same memory again can try that and handle the error rather than check this first.

Example

region.close() if not region.memory_released: ... slab = bytearray(len(slab)) # the old one may still be written

window(offset=0, length=None)

The span of this region a transfer should use.

Parameters:

Name Type Description Default
offset int

Where the window starts. Defaults to 0.

0
length Optional[int]

How many bytes it covers. If not set, the rest of the region from offset.

None

Returns:

Name Type Description
RdmaWindow RdmaWindow

The window, to pass to rdma_get or rdma_set.

Raises:

Type Description
RdmaError

If the region is closed or the window runs outside it.

Example

region.window() # the whole region region.window(4096, 1024) # 1 KiB starting 4 KiB in

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def window(self, offset: int = 0, length: Optional[int] = None) -> RdmaWindow:
    """
    The span of this region a transfer should use.

    Args:
        offset (int): Where the window starts. Defaults to 0.
        length (Optional[int]): How many bytes it covers. If not set, the
            rest of the region from ``offset``.

    Returns:
        RdmaWindow: The window, to pass to ``rdma_get`` or ``rdma_set``.

    Raises:
        RdmaError: If the region is closed or the window runs outside it.

    Example:
        >>> region.window()            # the whole region
        >>> region.window(4096, 1024)  # 1 KiB starting 4 KiB in
    """
    self._require_open()

    if offset < 0:
        raise RdmaError(f"offset must not be negative, got {offset}")
    if offset > self._capacity:
        raise RdmaError(
            f"offset {offset} is past the end of a region of "
            f"{self._capacity} bytes"
        )

    if length is None:
        length = self._capacity - offset
    elif length < 0:
        raise RdmaError(f"length must not be negative, got {length}")
    elif offset + length > self._capacity:
        raise RdmaError(
            f"window [{offset}, {offset + length}) runs past the end of a "
            f"region of {self._capacity} bytes"
        )

    return RdmaWindow(self, offset, length)

memoryview()

A view of the registered memory as a span of bytes.

Raises:

Type Description
RdmaError

If the region has been closed.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
502
503
504
505
506
507
508
509
510
def memoryview(self) -> memoryview:
    """
    A view of the registered memory as a span of bytes.

    Raises:
        RdmaError: If the region has been closed.
    """
    self._require_open()
    return memoryview(self._memory).cast("B")

close()

Deregister the memory and release the pinned pages.

The caller's buffer is not freed. Usually it can be reused or freed once this returns. The exception is a region a transfer closed on the tcp provider, or whose deregistration failed: a write may still land in it, so GLIDE keeps the buffer referenced until the fabric is done with it, and the caller should not reuse it either. On tcp that is once the client and all its regions are closed; after a failed deregistration, which is logged as an error, it is never. :attr:memory_released says which. Closing twice is a no-op, so this is safe in a finally.

This is not a way to cancel a transfer. To cancel one in flight, close the client from another thread: the transfer then closes its region on the way out, so closing it again is a no-op.

Raises:

Type Description
RdmaError

If a transfer is using the region. Closing it then would free the region under the transfer.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
def close(self) -> None:
    """
    Deregister the memory and release the pinned pages.

    The caller's buffer is not freed. Usually it can be reused or freed once
    this returns. The exception is a region a transfer closed on the tcp
    provider, or whose deregistration failed: a write may still land in it,
    so GLIDE keeps the buffer referenced until the fabric is done with it,
    and the caller should not reuse it either. On tcp that is once the
    client and all its regions are closed; after a failed deregistration,
    which is logged as an error, it is never. :attr:`memory_released` says
    which. Closing twice is a no-op, so this is safe in a ``finally``.

    This is not a way to cancel a transfer. To cancel one in flight, close
    the client from another thread: the transfer then closes its region on
    the way out, so closing it again is a no-op.

    Raises:
        RdmaError: If a transfer is using the region. Closing it then would
            free the region under the transfer.
    """
    with self._lock:
        if self._busy:
            raise RdmaError(
                "this RDMA region is in use by a transfer, so it cannot be "
                "closed yet; close the client to cancel the transfer, which "
                "then closes the region itself"
            )
        self._close_locked()

BaseClient

Bases: CoreCommands

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
class BaseClient(CoreCommands):

    def __init__(self, config: BaseClientConfiguration):
        """
        To create a new client, use the `create` classmethod
        """
        _glide_ffi = _SYNC_FFI
        self._ffi = _glide_ffi.ffi
        self._lib = _glide_ffi.lib
        self._config: BaseClientConfiguration = config
        self._pubsub_queue: List[PubSubMsg] = []
        self._pubsub_lock = threading.Lock()
        self._pubsub_condition = threading.Condition(self._pubsub_lock)
        self._pubsub_callback_ref = None  # Keep callback alive
        self._credential_provider_callback_ref = None
        self._credential_provider_callback_owner = None
        self._core_client = self._ffi.NULL
        # Lock protecting _core_client and _is_closed for free-threading safety.
        # Under GIL builds this is a no-op (GIL serializes access).
        # Under free-threaded builds this prevents use-after-free on concurrent close.
        self._client_lock = threading.Lock()
        # How many RDMA FFI calls are using `_core_client`. Guarded by
        # `_client_lock`. `close` cannot free the native client under them, so
        # it cancels their transfers instead and leaves the freeing to the last
        # one out.
        self._rdma_calls = 0
        # The native client `close` left for the last RDMA call to free.
        self._deferred_core_client = self._ffi.NULL
        # The callbacks that native client can still call, kept until it is
        # freed.
        self._deferred_callback_refs: Tuple[Any, ...] = ()

        self._is_closed: bool = False

    @classmethod
    def create(cls, config: BaseClientConfiguration) -> Self:
        if not isinstance(
            config, (GlideClientConfiguration, GlideClusterClientConfiguration)
        ):
            raise ConfigurationError(
                "Configuration must be an instance of the sync version of GlideClientConfiguration or GlideClusterClientConfiguration, imported from glide_sync.config."
            )
        self = cls(config)
        self._config = config
        self._is_closed = False

        os.register_at_fork(after_in_child=self._create_core_client)

        self._create_core_client()

        return self

    def _create_core_client(self):  # noqa: C901
        previous_owner = self._credential_provider_callback_owner
        if previous_owner is not None:
            previous_owner.close()
        self._credential_provider_callback_owner = None
        self._credential_provider_callback_ref = None
        # After a fork, the child has none of the parent's threads, so none of
        # the RDMA calls the parent had running will ever end here.
        self._rdma_calls = 0
        self._deferred_core_client = self._ffi.NULL
        self._deferred_callback_refs = ()
        credential_provider = None
        if (
            self._config.credentials is not None
            and self._config.credentials.iam_config is not None
        ):
            credential_provider = (
                self._config.credentials.iam_config.credential_provider
            )
        if credential_provider is not None and _is_async_callable(credential_provider):
            raise ConfigurationError(
                "The sync client does not support async credential providers; use the async client"
            )

        # This check is needed in case a fork happens after the client already closed
        # In that case the registered fork function will kick in even if the
        # client already closed, and recreate it anyway.
        if self._is_closed:
            return
        conn_req = _create_sync_connection_request(self._config)
        conn_req_bytes = conn_req.SerializeToString()
        # Store for scoped_connection
        self._conn_req_bytes = conn_req_bytes
        client_type = self._ffi.new(
            "ClientType*",
            {
                "_type": self._ffi.cast("ClientTypeEnum", FFIClientTypeEnum.Sync),
            },
        )

        # Always create pubsub callback to support dynamic subscriptions
        # This ensures messages are always handled by the wrapper, whether they originate
        # from configured subscriptions or from dynamic subscriptions added at runtime
        python_callback = self._create_push_handle_callback()
        pubsub_callback = self._ffi.callback("PubSubCallback", python_callback)
        # Store reference to prevent garbage collection
        self._pubsub_callback_ref = pubsub_callback

        # Create address resolver callback if configured
        address_resolver_callback = self._ffi.NULL
        if self._config.address_resolver is not None:
            resolver_fn = self._config.address_resolver

            def _address_resolver_callback(
                client_id,
                host_ptr,
                host_len,
                port,
                resolved_host_buf,
                resolved_host_buf_len,
                resolved_host_len_ptr,
            ):
                try:
                    host = self._ffi.buffer(host_ptr, host_len)[:].decode("utf-8")
                    resolved_host, resolved_port = resolver_fn(host, port)
                    encoded_host = resolved_host.encode("utf-8")
                    write_len = min(len(encoded_host), resolved_host_buf_len)
                    self._ffi.memmove(resolved_host_buf, encoded_host, write_len)
                    resolved_host_len_ptr[0] = write_len
                    return resolved_port
                except Exception:
                    # On error, return 0 to signal fallback to original address
                    return 0

            address_resolver_callback = self._ffi.callback(
                "AddressResolverCallback", _address_resolver_callback
            )
            # Store reference to prevent garbage collection
            self._address_resolver_callback_ref = address_resolver_callback

        if credential_provider is None:
            # Preserve the ordinary latest-main creation path exactly.
            client_response_ptr = self._lib.create_client(
                conn_req_bytes,
                len(conn_req_bytes),
                client_type,
                pubsub_callback,
                address_resolver_callback,
                0,  # client_id is not used by the Python client
            )

            Logger.log(Level.INFO, "connection info", "new connection established")

            # Handle the connection response
            if client_response_ptr != self._ffi.NULL:
                client_response = self._try_ffi_cast(
                    "ConnectionResponse*", client_response_ptr
                )
                if client_response.conn_ptr != self._ffi.NULL:
                    self._core_client = client_response.conn_ptr
                else:
                    error_message = (
                        self._ffi.string(
                            client_response.connection_error_message
                        ).decode(ENCODING)
                        if client_response.connection_error_message != self._ffi.NULL
                        else "Unknown error"
                    )
                    error_class = get_connection_error_class(
                        client_response.connection_error_type
                    )
                    self._lib.free_connection_response(client_response_ptr)
                    raise error_class(error_message)

                # Free the connection response to avoid memory leaks
                self._lib.free_connection_response(client_response_ptr)

                # Note: scope prewarm is deferred to first scoped_connection() call
                # to avoid creating extra connections at client startup (which breaks
                # lazy connection tests and connection count assertions).
            else:
                raise ClosingError("Failed to create client, response pointer is NULL.")
            return

        credential_callback, credential_owner = create_credential_provider_callback(
            self._ffi,
            credential_provider,
            allow_async=False,
            provider_owner=self,
        )
        try:
            client_response_ptr = self._lib.create_client_with_credential_provider(
                conn_req_bytes,
                len(conn_req_bytes),
                client_type,
                pubsub_callback,
                address_resolver_callback,
                credential_owner.callback_id,
                credential_callback,
            )
        except BaseException:
            credential_owner.close()
            raise

        Logger.log(Level.INFO, "connection info", "new connection established")

        if client_response_ptr == self._ffi.NULL:
            credential_owner.close()
            raise ClosingError("Failed to create client, response pointer is NULL.")

        client_response = self._try_ffi_cast("ConnectionResponse*", client_response_ptr)
        if client_response.conn_ptr == self._ffi.NULL:
            error_message = (
                self._ffi.string(client_response.connection_error_message).decode(
                    ENCODING
                )
                if client_response.connection_error_message != self._ffi.NULL
                else "Unknown error"
            )
            error_class = get_connection_error_class(
                client_response.connection_error_type
            )
            credential_owner.close()
            self._lib.free_connection_response(client_response_ptr)
            raise error_class(error_message)

        core_client = client_response.conn_ptr
        self._lib.free_connection_response(client_response_ptr)
        with self._client_lock:
            if self._is_closed:
                adopt_client = False
            else:
                self._core_client = core_client
                self._credential_provider_callback_ref = credential_callback
                self._credential_provider_callback_owner = credential_owner
                adopt_client = True
        if not adopt_client:
            credential_owner.close()
            self._lib.close_client(core_client)
            raise ClosingError("Client was closed during native creation.")

    def _create_push_handle_callback(self):
        """Create the FFI pubsub callback function"""

        def _pubsub_callback(
            client_ptr,
            kind,
            message_ptr,
            message_len,
            channel_ptr,
            channel_len,
            pattern_ptr,
            pattern_len,
        ):
            try:
                # Convert C pointers to Python bytes using ffi.buffer
                message = self._ffi.buffer(message_ptr, message_len)[:]
                channel = self._ffi.buffer(channel_ptr, channel_len)[:]
                pattern = (
                    self._ffi.buffer(pattern_ptr, pattern_len)[:]
                    if pattern_ptr != self._ffi.NULL
                    else None
                )

                push_kind_map = {
                    0: "Disconnection",
                    1: "Other",
                    2: "Invalidate",
                    3: "Message",
                    4: "PMessage",
                    5: "SMessage",
                    6: "Unsubscribe",
                    7: "PUnsubscribe",
                    8: "SUnsubscribe",
                    9: "Subscribe",
                    10: "PSubscribe",
                    11: "SSubscribe",
                }

                message_kind = push_kind_map.get(kind)

                if message_kind == "Disconnection":
                    Logger.log(
                        Level.WARN,
                        "disconnect notification",
                        "Transport disconnected, messages might be lost",
                    )
                elif message_kind in ["Message", "PMessage", "SMessage"]:
                    pubsub_msg = PubSubMsg(
                        message=message, channel=channel, pattern=pattern
                    )

                    # This aquires the underlying `_pubsub_lock` and allows for calling `notify()` on the variable
                    # If a callback is registered, call it with the message and the provided context
                    # Otherwise, append the message to the queue and notify threads that are waiting for a message.
                    with self._pubsub_condition:
                        user_callback, context = (
                            self._config._get_pubsub_callback_and_context()
                        )
                        if user_callback:
                            user_callback(pubsub_msg, context)
                        else:
                            self._pubsub_queue.append(pubsub_msg)
                            self._pubsub_condition.notify()
                elif message_kind in [
                    "PSubscribe",
                    "Subscribe",
                    "SSubscribe",
                    "Unsubscribe",
                    "PUnsubscribe",
                    "SUnsubscribe",
                ]:
                    pass  # Ignore subscription confirmations
                else:
                    Logger.log(
                        Level.WARN,
                        "unknown notification",
                        f"Unknown notification message: '{message_kind}'",
                    )

            except Exception as e:
                Logger.log(
                    Level.ERROR, "pubsub_callback", f"Error in pubsub callback: {e}"
                )

        return _pubsub_callback

    def _handle_response(self, message):
        if message == self._ffi.NULL:
            raise RequestError("Received NULL message.")
        addr = int(self._ffi.cast("uintptr_t", message))
        result, _arena_ptr = _fast_parse_response(addr)
        # Arena is freed by free_command_result in _handle_cmd_result's finally block
        return result

    def _handle_command_response(self, msg):
        """Handle a CommandResponse message based on its response type."""
        handlers = {
            0: self._handle_null_response,
            1: self._handle_int_response,
            2: self._handle_float_response,
            3: self._handle_bool_response,
            4: self._handle_string_response,
            5: self._handle_array_response,
            6: self._handle_map_response,
            7: self._handle_set_response,
            8: self._handle_ok_response,
            9: self._handle_error_response,
        }

        handler = handlers.get(msg.response_type)
        if handler is None:
            raise RequestError(f"Unhandled response type = {msg.response_type}")

        return handler(msg)

    def _handle_null_response(self, msg):
        return None

    def _handle_int_response(self, msg):
        return msg.int_value

    def _handle_float_response(self, msg):
        return msg.float_value

    def _handle_bool_response(self, msg):
        return bool(msg.bool_value)

    def _handle_string_response(self, msg):
        try:
            return self._ffi.buffer(msg.string_value, msg.string_value_len)[:]
        except Exception as e:
            raise RequestError(f"Error decoding string value: {e}")

    def _handle_array_response(self, msg):
        array = []
        for i in range(msg.array_value_len):
            element = self._try_ffi_cast("struct CommandResponse*", msg.array_value + i)
            array.append(self._handle_response(element))
        return array

    def _handle_map_response(self, msg):
        map_dict = {}
        for i in range(msg.array_value_len):
            element = self._try_ffi_cast("struct CommandResponse*", msg.array_value + i)
            key = self._try_ffi_cast("struct CommandResponse*", element.map_key)
            value = self._try_ffi_cast("struct CommandResponse*", element.map_value)
            map_dict[self._handle_response(key)] = self._handle_response(value)
        return map_dict

    def _handle_set_response(self, msg):
        result_set = set()
        sets_array = self._try_ffi_cast(
            f"struct CommandResponse[{msg.sets_value_len}]", msg.sets_value
        )
        for i in range(msg.sets_value_len):
            element = sets_array[i]
            result_set.add(self._handle_response(element))
        return result_set

    def _handle_ok_response(self, msg):
        return OK

    def _handle_error_response(self, msg):
        try:
            error_msg = self._ffi.buffer(msg.string_value, msg.string_value_len)[:]
            return RequestError(f"{error_msg}")
        except Exception as e:
            raise RequestError(f"Error decoding error message: {e}")

    def _try_ffi_cast(self, type, source):
        try:
            return self._ffi.cast(type, source)
        except Exception as e:
            raise ClosingError(f"FFI casting failed: {e}")

    def _to_c_strings(self, args):
        """Convert Python arguments to C-compatible pointers and lengths."""
        c_strings = []
        string_lengths = []
        buffers = []  # Keep a reference to prevent premature garbage collection

        for arg in args:
            arg_bytes, arg_len = _arg_buffer(arg)

            # Use ffi.from_buffer for zero-copy conversion
            buffers.append(arg_bytes)  # Keep the byte buffer alive
            c_strings.append(
                self._try_ffi_cast("size_t", self._ffi.from_buffer(arg_bytes))
            )
            string_lengths.append(arg_len)
        # Return C-compatible arrays and keep buffers alive
        return (
            self._ffi.new("size_t[]", c_strings),
            self._ffi.new("unsigned long[]", string_lengths),
            buffers,  # Ensure buffers stay alive
        )

    # `route_bytes` must remain alive for the duration of the FFI call that consumes `route_ptr`
    def _to_c_route_ptr_and_len(self, route: Optional[Route]):
        proto_route = build_protobuf_route(route)
        if proto_route:
            route_bytes = proto_route.SerializeToString()
            route_ptr = self._ffi.from_buffer(route_bytes)
            route_len = len(route_bytes)
        else:
            route_bytes = None
            route_ptr = self._ffi.NULL
            route_len = 0

        return route_ptr, route_len, route_bytes

    def _handle_cmd_result(self, command_result):
        try:
            if command_result == self._ffi.NULL:
                raise ClosingError("Internal error: Received NULL as a command result")
            if command_result.command_error != self._ffi.NULL:
                # Handle the error case
                error = self._try_ffi_cast(
                    "CommandError*", command_result.command_error
                )
                error_message = self._ffi.string(error.command_error_message).decode(
                    ENCODING
                )
                error_class = get_request_error_class(error.command_error_type)
                # Free the error message to avoid memory leaks
                raise error_class(error_message)
            else:
                return self._handle_response(command_result.response)
                # Free the error message to avoid memory leaks
        finally:
            self._lib.free_command_result(command_result)

    @staticmethod
    def _validate_response_buffers(response_buffers: List[memoryview]) -> None:
        """Each buffer for a multi-value read must be writable and contiguous."""
        for mv in response_buffers:
            if mv.readonly:
                raise TypeError("response_buffers entries must be writable")
            if not mv.c_contiguous:
                raise TypeError("response_buffers entries must be C-contiguous")

    def _execute_command(
        self,
        request_type: RequestType.ValueType,  # type: ignore[override]
        args: List[TEncodable],
        route: Optional[Route] = None,
        response_buffer: Optional[memoryview] = None,
        response_buffers: Optional[List[memoryview]] = None,
    ) -> TResult:
        if self._is_closed:
            raise ClosingError(
                "Unable to execute requests; the client is closed. Please create a new client."
            )
        client_adapter_ptr = self._core_client
        if client_adapter_ptr == self._ffi.NULL:
            raise ValueError("Invalid client pointer.")
        if response_buffer:
            if response_buffer.readonly:
                raise TypeError("response_buffer must be writable")
            if not response_buffer.c_contiguous:
                raise TypeError("response_buffer must be C-contiguous")
        if response_buffers is not None:
            self._validate_response_buffers(response_buffers)

        # Sample before reading the caller's context. A sampled command span uses
        # the active OTel span as its parent when one is available.
        from .opentelemetry import OpenTelemetry

        span = 0
        span_name_cstr = None
        if OpenTelemetry.is_tracing_enabled() and OpenTelemetry.should_sample():
            parent_ctx = OpenTelemetry._get_parent_span_context()
            command_name = RequestType.Name(request_type)
            span_name_cstr = self._ffi.new("char[]", command_name.encode())
            span = _create_command_span(
                self._ffi, self._lib, span_name_cstr, parent_ctx
            )

        try:
            # Convert the arguments to C-compatible pointers
            c_args, c_lengths, buffers = self._to_c_strings(args)

            # Route bytes should be kept alive in the scope of the FFI call
            route_ptr, route_len, route_bytes = self._to_c_route_ptr_and_len(route)

            if response_buffers is not None:
                # One writable buffer per top-level array element (e.g. mget):
                # each value is copied straight into its caller-owned buffer.
                # The from_buffer cdata must stay alive for the call, so keep
                # the list referenced until command_with_buffers returns.
                target_ptrs = [self._ffi.from_buffer(mv) for mv in response_buffers]
                target_bufs = self._ffi.new("uint8_t*[]", target_ptrs)
                target_lens = self._ffi.new(
                    "size_t[]", [mv.nbytes for mv in response_buffers]
                )
                result = self._lib.command_with_buffers(
                    client_adapter_ptr,
                    0,
                    request_type,
                    len(args),
                    c_args,
                    c_lengths,
                    route_ptr,
                    route_len,
                    target_bufs,
                    target_lens,
                    len(response_buffers),
                    span,
                )
            else:
                buf_ptr = (
                    self._ffi.from_buffer(response_buffer)
                    if response_buffer
                    else self._ffi.NULL
                )
                # Capacity must be expressed in bytes, not elements. ``len()`` on
                # a memoryview returns the element count (``shape[0]``), which
                # equals the byte count only for itemsize-1 formats (e.g. "B").
                buf_len = response_buffer.nbytes if response_buffer else 0
                result = self._lib.command_with_buffer(
                    client_adapter_ptr,
                    0,
                    request_type,
                    len(args),
                    c_args,
                    c_lengths,
                    route_ptr,
                    route_len,
                    buf_ptr,
                    buf_len,
                    span,
                )
        finally:
            # Drop span if it was created
            if span != 0:
                self._lib.drop_otel_span(span)
        return self._handle_cmd_result(result)

    def _update_connection_password(
        self,
        password: Optional[str],
        immediate_auth: bool = False,
    ) -> TResult:
        """
        Update the current connection password with a new password.

        Note:
            This method updates the client's internal password configuration and does
            not perform password rotation on the server side.

        This method is useful in scenarios where the server password has changed or when
        utilizing short-lived passwords for enhanced security. It allows the client to
        update its password to reconnect upon disconnection without the need to recreate
        the client instance. This ensures that the internal reconnection mechanism can
        handle reconnection seamlessly, preventing the loss of in-flight commands.

        Args:
            password (`Optional[str]`): The new password to use for the connection,
                if `None` the password will be removed.
            immediate_auth (`bool`):
                `True`: The client will authenticate immediately with the new password against all connections, Using `AUTH`
                command. If password supplied is an empty string, auth will not be performed and warning will be returned.
                The default is `False`.

        Returns:
            TOK: A simple OK response. If `immediate_auth=True` returns OK if the reauthenticate succeed.

        Example:
            >>> client.update_connection_password("new_password", immediate_auth=True)
            'OK'
        """
        if self._is_closed:
            raise ClosingError("Client is closed.")
        client_adapter_ptr = self._core_client
        if client_adapter_ptr == self._ffi.NULL:
            raise ValueError("Invalid client pointer.")

        # Prepare C string for password
        c_password = (
            self._ffi.new("char[]", password.encode(ENCODING))
            if password is not None
            else self._ffi.new("char[]", b"")
        )

        result = self._lib.update_connection_password(
            client_adapter_ptr,
            0,  # Request ID (0 for sync use)
            c_password,
            immediate_auth,
        )
        return self._handle_cmd_result(result)

    def _refresh_iam_token(self) -> TResult:
        if self._is_closed:
            raise ClosingError("Client is closed.")
        client_adapter_ptr = self._core_client
        if client_adapter_ptr == self._ffi.NULL:
            raise ValueError("Invalid client pointer.")

        result = self._lib.refresh_iam_token(
            client_adapter_ptr,
            0,  # Request ID (0 for sync use)
        )
        return self._handle_cmd_result(result)

    def _execute_batch(
        self,
        commands: List[Tuple[RequestType.ValueType, List[TEncodable]]],  # type: ignore[override]
        is_atomic: bool,
        raise_on_error: bool,
        retry_server_error: bool = False,
        retry_connection_error: bool = False,
        route: Optional[Route] = None,
        timeout: Optional[int] = None,
    ) -> List[TResult]:
        """
        Execute a batch of commands synchronously using the FFI batch function.
        Accepts pre-extracted parameters from exec().
        """

        if self._is_closed:
            raise ClosingError(
                "Unable to execute requests; the client is closed. Please create a new client."
            )

        client_adapter_ptr = self._core_client
        if client_adapter_ptr == self._ffi.NULL:
            raise ValueError("Invalid client pointer.")

        # Create span if OpenTelemetry is configured and sampling indicates we should trace
        from .opentelemetry import OpenTelemetry

        span = 0
        if OpenTelemetry.is_tracing_enabled() and OpenTelemetry.should_sample():
            parent_ctx = OpenTelemetry._get_parent_span_context()
            span = _create_batch_span(self._ffi, self._lib, parent_ctx)

        try:
            # Note: batch_refs and option_refs must remain in scope
            # throughout this entire function call to prevent garbage collection of Python objects
            # that have C pointers pointing to them via ffi.from_buffer().

            # Convert commands + atomic flag to C BatchInfo
            batch_info, batch_refs = self._convert_commands_to_c_batch_info(
                commands, is_atomic
            )

            # Create batch options from extracted parameters
            batch_options, option_refs = self._create_c_batch_options_from_params(
                retry_server_error, retry_connection_error, route, timeout
            )

            result = self._lib.batch(
                client_adapter_ptr,
                0,  # callback_index (0 for sync)
                batch_info,
                raise_on_error,
                batch_options,
                span,  # span_ptr for tracing
            )
            return self._handle_cmd_result(result)
        finally:
            # Drop span if it was created
            if span != 0:
                self._lib.drop_otel_span(span)

    def _convert_commands_to_c_batch_info(
        self,
        commands: List[Tuple[RequestType.ValueType, List[TEncodable]]],
        is_atomic: bool,
    ) -> Tuple[Any, List[Any]]:
        """
        Convert commands directly to C BatchInfo (no intermediate _to_c_strings).
        Returns a tuple of (batch_info, refs) where refs contains all Python objects
        that must be kept alive to prevent garbage collection while C code uses pointers to them.
        """
        # all_refs keeps Python objects alive while C pointers reference their memory.
        # ffi.from_buffer() creates C pointers to Python object memory, and ffi.new() creates
        # FFI-managed memory with a Python reference controlling its lifetime. In both cases,
        # if Python references are garbage collected, the underlying memory may be freed,
        # creating dangling C pointers.

        all_refs = []
        cmd_infos = []

        for request_type, args in commands:
            args_buffers = []
            arg_ptrs = []
            arg_lengths = []

            for arg in args:
                arg_bytes, arg_len = _arg_buffer(arg)

                args_buffers.append(arg_bytes)
                arg_ptrs.append(self._ffi.from_buffer(arg_bytes))
                arg_lengths.append(arg_len)

            c_arg_array = self._ffi.new("const uint8_t*[]", arg_ptrs)
            c_lengths = self._ffi.new("size_t[]", arg_lengths)

            cmd_info = self._ffi.new(
                "CmdInfo*",
                {
                    "request_type": request_type,
                    "args": c_arg_array,
                    "arg_count": len(args),
                    "args_len": c_lengths,
                },
            )

            cmd_infos.append(cmd_info)
            all_refs.extend(args_buffers + [c_arg_array, c_lengths])

        cmd_info_array = self._ffi.new("const CmdInfo*[]", cmd_infos)
        all_refs.append(cmd_info_array)
        all_refs.extend(cmd_infos)

        batch_info = self._ffi.new(
            "BatchInfo*",
            {
                "cmd_count": len(commands),
                "cmds": cmd_info_array,
                "is_atomic": is_atomic,
            },
        )

        return batch_info, all_refs + [batch_info]

    def _create_c_batch_options_from_params(
        self,
        retry_server_error: bool,
        retry_connection_error: bool,
        route: Optional[Route],
        timeout: Optional[int],
    ) -> Tuple[Any, List[Any]]:
        """
        Create BatchOptionsInfo from params, with refs.
        Returns a tuple of (batch_options, refs) where refs contains all Python objects
        that must be kept alive while C code accesses pointers to them.
        """

        route_info, route_refs = self._convert_route_to_c_format(route)

        batch_options = self._ffi.new(
            "BatchOptionsInfo*",
            {
                "retry_server_error": retry_server_error,
                "retry_connection_error": retry_connection_error,
                "has_timeout": timeout is not None,
                "timeout": timeout or 0,
                "route_info": route_info,
            },
        )

        return batch_options, route_refs + [batch_options]

    def _convert_route_to_c_format(
        self, route: Optional[Route]
    ) -> Tuple[Any, List[Any]]:
        """
        Convert a Route object to C RouteInfo format.

        Returns a tuple of (route_info, refs) where refs contains all Python objects
        that must be kept alive while C code uses pointers to them.
        """
        if route is None:
            return self._ffi.NULL, []

        refs = []

        slot_key_ptr = self._ffi.NULL
        hostname_ptr = self._ffi.NULL
        route_type = 2  # Default to Random
        slot_id = 0
        slot_type = 0  # Primary by default
        port = 0

        if isinstance(route, AllNodes):
            route_type = 0
        elif isinstance(route, AllPrimaries):
            route_type = 1
        elif isinstance(route, RandomNode):
            route_type = 2
        elif isinstance(route, SlotIdRoute):
            route_type = 3
            slot_id = route.slot_id
            slot_type = 0 if route.slot_type == SlotType.PRIMARY else 1
        elif isinstance(route, SlotKeyRoute):
            route_type = 4
            # Null termination needed for safety instructions of the FFI layer's `ptr_to_str` call.
            slot_key_bytes = route.slot_key.encode(ENCODING) + b"\0"
            refs.append(slot_key_bytes)
            slot_key_ptr = self._ffi.from_buffer(slot_key_bytes)
            slot_type = 0 if route.slot_type == SlotType.PRIMARY else 1
        elif isinstance(route, ByAddressRoute):
            route_type = 5
            # Null termination needed for safety instructions of the FFI layer's `ptr_to_str` call.
            hostname_bytes = route.host.encode(ENCODING) + b"\0"
            refs.append(hostname_bytes)
            hostname_ptr = self._ffi.from_buffer(hostname_bytes)
            port = route.port if route.port is not None else 0
        else:
            raise RequestError(f"Invalid route type: {type(route)}")

        route_info = self._ffi.new(
            "RouteInfo*",
            {
                "route_type": route_type,
                "slot_id": slot_id,
                "slot_key": slot_key_ptr,
                "slot_type": slot_type,
                "hostname": hostname_ptr,
                "port": port,
            },
        )

        return route_info, refs + [route_info]

    def _execute_script(
        self,
        script_hash: str,
        keys: Optional[List[TEncodable]] = None,
        args: Optional[List[TEncodable]] = None,
        route: Optional[Route] = None,
    ) -> TResult:

        if self._is_closed:
            raise ClosingError(
                "Unable to execute requests; the client is closed. Please create a new client."
            )

        client_adapter_ptr = self._core_client
        if client_adapter_ptr == self._ffi.NULL:
            raise ValueError("Invalid client pointer.")

        # Default to empty lists if None provided
        if keys is None:
            keys = []
        if args is None:
            args = []

        # Convert keys to C-compatible format
        keys_c_args, keys_c_lengths, keys_buffers = self._to_c_strings(keys)

        # Convert args to C-compatible format
        args_c_args, args_c_lengths, args_buffers = self._to_c_strings(args)

        # Convert script hash to C string
        hash_bytes = script_hash.encode(ENCODING) + b"\0"
        hash_buffer = self._ffi.from_buffer(hash_bytes)

        # Route bytes should be kept alive in the scope of the FFI call
        route_ptr, route_len, route_bytes = self._to_c_route_ptr_and_len(route)

        # Create span if OpenTelemetry is configured and sampling
        from .opentelemetry import OpenTelemetry

        span = 0
        if OpenTelemetry.is_tracing_enabled() and OpenTelemetry.should_sample():
            parent_ctx = OpenTelemetry._get_parent_span_context()
            span = _create_command_span(
                self._ffi, self._lib, _EVALSHA_SPAN_NAME, parent_ctx
            )

        try:
            result = self._lib.invoke_script(
                client_adapter_ptr,
                0,  # Request ID - placeholder for sync clients
                hash_buffer,
                len(keys),
                keys_c_args,
                keys_c_lengths,
                len(args),
                args_c_args,
                args_c_lengths,
                route_ptr,
                route_len,
                span,
            )
            return self._handle_cmd_result(result)
        finally:
            if span != 0:
                self._lib.drop_otel_span(span)

    def try_get_pubsub_message(self) -> Optional[PubSubMsg]:
        """Try to get a pubsub message without blocking"""
        if self._is_closed:
            raise ClosingError(
                "Unable to execute requests; the client is closed. Please create a new client."
            )

        if self._config._get_pubsub_callback_and_context()[0] is not None:
            raise ConfigurationError(
                "The operation will never succeed since messages will be passed to the configured callback."
            )

        with self._pubsub_condition:
            if self._pubsub_queue:
                return self._pubsub_queue.pop(0)
            else:
                return None

    def get_pubsub_message(self) -> PubSubMsg:
        """Get a pubsub message, blocking until one is available"""
        if self._is_closed:
            raise ClosingError(
                "Unable to execute requests; the client is closed. Please create a new client."
            )

        if self._config._get_pubsub_callback_and_context()[0] is not None:
            raise ConfigurationError(
                "The operation will never complete since messages will be passed to the configured callback."
            )

        with self._pubsub_condition:
            while not self._pubsub_queue:
                if self._is_closed:
                    raise ClosingError("Client was closed while waiting for message")

                # Block indefinitely until notify() is called
                self._pubsub_condition.wait()

            return self._pubsub_queue.pop(0)

    def get_statistics(self) -> dict:
        """
        Get compression and connection statistics for this client.

        Returns:
            dict: A dictionary containing statistics with integer values:
                - total_connections: Total number of connections
                - total_clients: Total number of clients
                - total_values_compressed: Number of values successfully compressed
                - total_values_decompressed: Number of values successfully decompressed
                - total_original_bytes: Total bytes of original data before compression
                - total_bytes_compressed: Total bytes after compression
                - total_bytes_decompressed: Total bytes after decompression
                - compression_skipped_count: Number of times compression was skipped
                - subscription_out_of_sync_count: Failed reconciliation attempts
                - subscription_last_sync_timestamp: Last successful sync (milliseconds since epoch)
        """
        # Call the C FFI get_statistics function (returns by value, no manual free needed)
        stats = self._lib.get_statistics()

        # Access the struct fields and convert to a dictionary
        return {
            "total_connections": stats.total_connections,
            "total_clients": stats.total_clients,
            "total_values_compressed": stats.total_values_compressed,
            "total_values_decompressed": stats.total_values_decompressed,
            "total_original_bytes": stats.total_original_bytes,
            "total_bytes_compressed": stats.total_bytes_compressed,
            "total_bytes_decompressed": stats.total_bytes_decompressed,
            "compression_skipped_count": stats.compression_skipped_count,
            "subscription_out_of_sync_count": stats.subscription_out_of_sync_count,
            "subscription_last_sync_timestamp": stats.subscription_last_sync_timestamp,
        }

    def get_subscriptions(self):
        """Get subscription state (desired vs actual)."""
        result = self._execute_command(RequestType.GetSubscriptions, [])
        return self._parse_pubsub_state(
            result, is_cluster=isinstance(self, GlideClusterClient)
        )

    def _parse_pubsub_state(self, result, is_cluster):
        """Parse subscription state from Rust response."""
        if not isinstance(result, list) or len(result) != 4:
            raise RequestError("Invalid response format from GetSubscriptions")

        desired_dict = result[1]
        actual_dict = result[3]

        if is_cluster:
            from glide_shared.config import GlideClusterClientConfiguration

            PubSubChannelModes = GlideClusterClientConfiguration.PubSubChannelModes
            StateClass = GlideClusterClientConfiguration.PubSubState
            mode_map = {
                "Exact": PubSubChannelModes.Exact,
                "Pattern": PubSubChannelModes.Pattern,
                "Sharded": PubSubChannelModes.Sharded,
            }
        else:
            from glide_shared.config import GlideClientConfiguration

            PubSubChannelModes = GlideClientConfiguration.PubSubChannelModes
            StateClass = GlideClientConfiguration.PubSubState
            mode_map = {
                "Exact": PubSubChannelModes.Exact,
                "Pattern": PubSubChannelModes.Pattern,
            }

        desired_subscriptions = {}
        actual_subscriptions = {}

        for key_bytes, value_list in desired_dict.items():
            key = key_bytes.decode() if isinstance(key_bytes, bytes) else key_bytes
            if key in mode_map:
                values = {v.decode() if isinstance(v, bytes) else v for v in value_list}
                desired_subscriptions[mode_map[key]] = values

        for key_bytes, value_list in actual_dict.items():
            key = key_bytes.decode() if isinstance(key_bytes, bytes) else key_bytes
            if key in mode_map:
                values = {v.decode() if isinstance(v, bytes) else v for v in value_list}
                actual_subscriptions[mode_map[key]] = values

        return StateClass(
            desired_subscriptions=desired_subscriptions,
            actual_subscriptions=actual_subscriptions,
        )

    def _get_cache_metrics(self, metrics_type: int) -> TResult:
        """
        Get cache metrics.

        Args:
            metrics_type: Type of metric to retrieve (e.g., hit rate, miss rate).

        Returns:
            The requested cache metric.

        Raises:
            RequestError: If client-side caching is not enabled or metrics tracking is disabled.
        """
        if self._is_closed:
            raise ClosingError("Client is closed.")
        client_adapter_ptr = self._core_client
        if client_adapter_ptr == self._ffi.NULL:
            raise ValueError("Invalid client pointer.")

        result = self._lib.get_cache_metrics(
            client_adapter_ptr,
            0,  # Request ID (0 for sync use)
            metrics_type,
        )
        return self._handle_cmd_result(result)

    @staticmethod
    def rdma_available() -> bool:
        """
        Whether this build of GLIDE has RDMA compiled in.

        A build from source without the RDMA feature returns false.

        This says nothing about whether libfabric is on the machine.
        For whether RDMA can actually happen here, use :meth:`rdma_usable`.

        Returns:
            bool: True if RDMA support is present in this build.

        Example:
            >>> BaseClient.rdma_available()
            True
        """
        return bool(_SYNC_FFI.lib.rdma_available())

    @staticmethod
    def rdma_usable() -> bool:
        """
        Whether this build has RDMA support and can load a compatible libfabric
        on this machine.

        It does not look for fabric hardware, so creating an RDMA client can
        still fail, for example with ``RdmaProvider.EfaDirect()`` on a machine
        without an EFA device.

        Returns:
            bool: True if libfabric loads and this build supports RDMA.

        Example:
            >>> BaseClient.rdma_usable()
            False
        """
        return bool(_SYNC_FFI.lib.rdma_usable())

    def register_rdma_region(self, memory: Any) -> RdmaRegion:
        """
        Register memory so the server can transfer into or out of it directly.

        The memory stays the caller's. Anything supporting the writable buffer
        protocol works: a ``bytearray``, an ``mmap``, a NumPy array, a tensor's
        backing store. It must not be resized or freed until the returned region
        is closed.

        Register one large region and address windows of it per transfer rather
        than registering per operation.

        Memory that GLIDE still holds from a closed region, which
        :attr:`RdmaRegion.memory_released` reports, is refused, because a write
        from that region's last transfer could still land in it. That includes
        any other view or slice of the same bytes. On efa-direct this happens
        only after a failed deregistration.

        Args:
            memory (Any): A writable, C-contiguous buffer to register.

        Returns:
            RdmaRegion: The registered region. Close when done with it.

        Raises:
            RdmaError: If this build has no RDMA support, the client was not
                configured for RDMA, the memory is still held from a closed
                region, or the fabric refused the registration.
            ClosingError: If the client is closed.
            TypeError: If the buffer is not writable and C-contiguous.

        Example:
            >>> region = client.register_rdma_region(bytearray(1 << 20))
            >>> region.capacity
            1048576
        """
        view = memoryview(memory)
        if view.readonly:
            raise TypeError("memory must be writable")
        if not view.c_contiguous:
            raise TypeError("memory must be C-contiguous")
        span = _memory_span(view)
        if _RETAINED_RDMA_MEMORY.overlaps(span):
            raise RdmaError(
                "this memory belongs to a closed RDMA region whose last transfer "
                "could still write into it; register different memory"
            )

        client_adapter_ptr = self._begin_rdma_call()
        buffer = self._ffi.from_buffer(view)
        try:
            registration = self._lib.register_rdma_region(
                client_adapter_ptr, buffer, view.nbytes
            )
            if registration == self._ffi.NULL:
                raise RdmaError(
                    "Internal error: received NULL from register_rdma_region"
                )
            try:
                if registration.error_message != self._ffi.NULL:
                    raise RdmaError(
                        self._ffi.string(registration.error_message).decode(ENCODING)
                    )
                region = registration.region
                try:
                    return RdmaRegion(self, memory, region)
                except BaseException:
                    # Until the RdmaRegion is built, nothing else will free the
                    # region, so free it here instead of leaking its pinned pages.
                    _free_rdma_region(
                        self._lib, self._ffi, region, memory, buffer, span
                    )
                    raise
            finally:
                self._lib.free_rdma_registration(registration)
        except BaseException:
            # The error's traceback keeps this frame alive, and with it `view`.
            # If the error ends up in a reference cycle, Python 3.9's garbage
            # collector crashes freeing a memoryview that `buffer` still holds
            # an export on, so let go of the export before the error leaves.
            del buffer
            raise
        finally:
            self._end_rdma_call()

    def rdma_get(
        self,
        key: TEncodable,
        window: RdmaWindow,
    ) -> Optional[RdmaReadReceipt]:
        """
        Read a value directly into a window of registered memory.

        Waits until the transfer completes. The bytes are in the window by the
        time this returns. The value never travels in the RESP reply.

        There is no timeout. The server moves the payload with a remote memory
        operation that nothing can call off once it is posted, so giving up
        early would leave the server writing into the window while the caller
        believed it was free.

        To cancel a transfer, call :meth:`close` on the client from another
        thread. That first cuts the server off from every region the client
        registered, then this call returns raising ``ClosingError``, unless
        the server's reply was already arriving, in which case it returns as
        usual. Bytes that landed before the close stay, so the window then
        holds an unknown mix of old and new bytes. See :meth:`close` for the
        rare case where the close cannot cancel the transfer.

        A transfer that ends before the server is known to be done with the
        memory closes the region, for example one cancelled that way or one
        whose connection was lost. See :class:`RdmaRegion` for every case and
        how to recover.

        Args:
            key (TEncodable): The key to read.
            window (RdmaWindow): Where the value should land, from
                :meth:`RdmaRegion.window`. The server is told the window's
                length and refuses a larger value before writing anything, so
                the bytes around the window are never touched.

        Returns:
            Optional[RdmaReadReceipt]: What the server transferred, or None if the
            key does not exist. The landed bytes have already been verified
            against the receipt's ``checksum``.

        Raises:
            RdmaError: If the region is closed, in use by another transfer, or
                belongs to another client; a ``MULTI`` is open on this client;
                the value was larger than the window (the region stays usable);
                the landed bytes did not match the checksum; or the server
                refused the transfer or its handshake.
            ConnectionError: If the connection failed, or has to be replaced
                because its handshake left it unusable. Check
                ``region.closed``: the region stays open when the transfer was
                never sent.
            ClosingError: If the client is closed, including when it is closed
                during the transfer to cancel it.
            TypeError: If ``window`` is not an ``RdmaWindow``.

        Example:
            >>> receipt = client.rdma_get(b"key", region.window(4096, 4096))
            >>> receipt.bytes_written if receipt else "missing"
        """
        c_key = self._to_c_key(key)
        return self._rdma_transfer(
            window,
            lambda client, region: self._lib.rdma_get(
                client, *c_key, region, window.offset, window.length
            ),
        )

    def rdma_set(
        self,
        key: TEncodable,
        window: RdmaWindow,
        checksum: Union[
            RdmaSetChecksum.Skip, RdmaSetChecksum.Compute, RdmaSetChecksum.Known
        ] = RdmaSetChecksum.Skip(),
    ) -> None:
        """
        Store a value the server reads directly out of a window of registered
        memory.

        As with ``rdma_get``, there is no timeout, closing the client from
        another thread cancels the call, raising ``ClosingError``, and a
        transfer that ends before the server is known to be done with the
        memory closes the region. See :class:`RdmaRegion` for how to recover.

        Args:
            key (TEncodable): The key to write.
            window (RdmaWindow): The bytes to send, from
                :meth:`RdmaRegion.window`.
            checksum: Whether the server checks the bytes it read against a
                CRC-32c before storing them; see :class:`RdmaSetChecksum`.
                Defaults to ``RdmaSetChecksum.Skip()``, which sends none.

        Returns:
            None. The server acknowledges without reporting a length, having
            read exactly the number of bytes the command named. A short read
            fails the transfer and raises instead.

        Raises:
            RdmaError: If the region is closed, in use by another transfer, or
                belongs to another client; a ``MULTI`` is open on this client;
                or the server refused the write or its handshake, including when
                the bytes it read do not match the checksum. A refused write
                stores nothing and leaves the region usable. If the region
                closed instead, the outcome is unknown: for example, a write
                the server queued inside another thread's ``MULTI`` may still
                be stored on ``EXEC``.
            ConnectionError: As for ``rdma_get``.
            ClosingError: If the client is closed, including when it is closed
                during the transfer to cancel it.
            TypeError: If ``window`` is not an ``RdmaWindow``, or ``checksum``
                is not an ``RdmaSetChecksum`` choice.
            ValueError: If a known checksum is not an unsigned 32-bit integer.

        Example:
            >>> window = region.window(0, 11)
            >>> window.memoryview()[:] = b"hello world"
            >>> client.rdma_set(b"key", window, checksum=RdmaSetChecksum.Compute())
        """
        checksum_mode, checksum_value = self._rdma_set_checksum(checksum)
        c_key = self._to_c_key(key)
        self._rdma_transfer(
            window,
            lambda client, region: self._lib.rdma_set(
                client,
                *c_key,
                region,
                window.offset,
                window.length,
                checksum_mode,
                checksum_value,
            ),
        )

    @staticmethod
    def rdma_checksum(data: Any) -> int:
        """
        CRC-32c of ``data``, the integrity check the RDMA protocol carries.

        The same value the server computes, so a caller can verify what landed
        after a read, or compute one before sending to pass to ``rdma_set`` as
        ``RdmaSetChecksum.Known``. ``rdma_get`` verifies every read against the
        checksum the server sends with its reply.

        Args:
            data (Any): Any bytes-like object.

        Returns:
            int: The CRC-32c, as an unsigned 32-bit integer.

        Raises:
            RdmaError: If this build has no RDMA support.

        Example:
            >>> GlideClient.rdma_checksum(b"123456789")
            3808858755
        """
        ffi, lib = _SYNC_FFI.ffi, _SYNC_FFI.lib
        # Check before `view` and `buffer` exist. An error raised while `buffer`
        # holds an export on `view` keeps both alive in its traceback, and
        # Python 3.9's garbage collector crashes if that error ends up in a
        # reference cycle.
        if not lib.rdma_available():
            raise RdmaError(
                "this build of GLIDE has no RDMA support compiled in, so it "
                "cannot compute a transfer checksum"
            )
        view = memoryview(data)
        out = ffi.new("uint32_t*")
        buffer = ffi.from_buffer(view) if view.nbytes else ffi.NULL
        if not lib.rdma_checksum(buffer, view.nbytes, out):
            raise RdmaError("Internal error: rdma_checksum failed")
        return int(out[0])

    def _begin_rdma_call(self):
        """
        The client pointer for one RDMA FFI call, or an error naming what went
        wrong. Until the matching `_end_rdma_call`, `close` will not free the
        native client.
        """
        with self._client_lock:
            if self._is_closed:
                raise ClosingError(
                    "Unable to execute requests; the client is closed. Please create a new client."
                )
            client_adapter_ptr = self._core_client
            if client_adapter_ptr == self._ffi.NULL:
                raise ValueError("Invalid client pointer.")
            self._rdma_calls += 1
            return client_adapter_ptr

    def _end_rdma_call(self) -> None:
        """
        End a call `_begin_rdma_call` began, and free the native client if
        `close` left that to the last call out and this is it.
        """
        with self._client_lock:
            self._rdma_calls -= 1
            core_client = self._deferred_core_client
            if self._rdma_calls > 0 or core_client == self._ffi.NULL:
                return
            self._deferred_core_client = self._ffi.NULL
            callback_refs = self._deferred_callback_refs
            self._deferred_callback_refs = ()
            owner = self._credential_provider_callback_owner
            self._credential_provider_callback_owner = None
        self._lib.close_client(core_client)
        # Now that the native client is closed, nothing can call the callbacks
        # or refresh the IAM token.
        if owner is not None:
            owner.close()
        del callback_refs
        # Closing the client may be what lets the fabric go of memory it held.
        _RETAINED_RDMA_MEMORY.release_what_is_free()

    def _to_c_key(self, key: TEncodable) -> Tuple[Any, int]:
        """A key as a pointer and a length, with the bytes kept alive by CFFI."""
        key_bytes = key.encode(ENCODING) if isinstance(key, str) else bytes(key)
        return self._ffi.from_buffer(key_bytes), len(key_bytes)

    def _rdma_set_checksum(self, checksum: Any) -> Tuple[Any, int]:
        """The checksum mode and value ``rdma_set`` passes across the FFI."""
        if isinstance(checksum, RdmaSetChecksum.Skip):
            return self._lib.RDMA_SET_CHECKSUM_SKIP, 0
        if isinstance(checksum, RdmaSetChecksum.Compute):
            return self._lib.RDMA_SET_CHECKSUM_COMPUTE, 0
        if isinstance(checksum, RdmaSetChecksum.Known):
            value = checksum.value
            if (
                not isinstance(value, int)
                or isinstance(value, bool)
                or not 0 <= value <= 0xFFFFFFFF
            ):
                raise ValueError(
                    "a known checksum must be an unsigned 32-bit integer, "
                    f"got {value!r}"
                )
            return self._lib.RDMA_SET_CHECKSUM_KNOWN, value
        raise TypeError(
            "checksum must be RdmaSetChecksum.Skip(), .Compute() or .Known(value), "
            f"got {type(checksum).__name__}"
        )

    def _rdma_transfer(
        self, window: RdmaWindow, call: Callable[[Any, Any], Any]
    ) -> Optional[RdmaReadReceipt]:
        """
        Run one transfer through `window`'s region with `call`, which takes the
        client and region pointers and makes the FFI call.

        Refuses a window that is not one, or whose region belongs to another
        client, then a closed client, then a region that is closed or already
        in use. The region stays marked in use until the FFI call returns, and
        is closed before it is released if the transfer left it unusable, so
        ``region.closed`` says so.
        """
        if not isinstance(window, RdmaWindow):
            raise TypeError(
                "window must be an RdmaWindow from region.window(), got "
                f"{type(window).__name__}"
            )
        region = window.region
        if region._client is not self:
            raise RdmaError(
                "this region is registered with a different client, so this "
                "client cannot transfer with it"
            )
        client_ptr = self._begin_rdma_call()
        try:
            region_ptr = region._begin_transfer()
            region_closed = False
            try:
                result = call(client_ptr, region_ptr)
                if result == self._ffi.NULL:
                    raise RdmaError("Internal error: received NULL as an RDMA result")
                region_closed = bool(result.region_closed)
                return self._handle_rdma_result(result)
            finally:
                region._end_transfer(close=region_closed)
        finally:
            self._end_rdma_call()

    def _handle_rdma_result(self, result) -> Optional[RdmaReadReceipt]:
        """
        Turn a non-null transfer result into a receipt and free it, raising on
        failure.

        None means the key was absent, meaning nothing was transferred and
        the window is untouched.

        A transfer cancelled by closing the client raises ``ClosingError``.
        Any other failure keeps its own class even if the client was closed,
        so a reply larger than the window or a checksum mismatch that happened
        just before the close is still reported.
        """
        try:
            if result.error_message != self._ffi.NULL:
                message = self._ffi.string(result.error_message).decode(ENCODING)
                if message.startswith(_RDMA_CANCELLED):
                    raise ClosingError(message)
                error_class = get_request_error_class(result.error_type)
                if error_class is RequestError:
                    error_class = RdmaError
                raise error_class(message)
            if not result.found:
                return None
            return RdmaReadReceipt(
                bytes_written=int(result.bytes_written),
                checksum=int(result.checksum) if result.has_checksum else None,
            )
        finally:
            self._lib.free_rdma_result(result)

    @property
    def closed(self) -> bool:
        """
        Whether :meth:`close` has been called. A closed client refuses every
        later command, registration, and transfer, so a new client is needed.
        After a failed RDMA transfer this says whether the region can be
        registered again on this client; see :class:`RdmaRegion`.

        Example:
            >>> client.close()
            >>> client.closed
            True
        """
        return self._is_closed

    def close(self) -> None:
        """
        Close the client. Closing twice is a no-op.

        With RDMA, this also cancels every transfer in flight on another thread:
        it cuts the server off from every region the client registered, and
        each blocked ``rdma_get`` or ``rdma_set`` then raises ``ClosingError``,
        unless its reply was already arriving, in which case it returns as
        usual.

        This returns without waiting for those calls. Close a region only after
        every transfer call using it has returned; while one is still running,
        :meth:`RdmaRegion.close` raises ``RdmaError``. A cancelled transfer
        closes its own region on the way out, so there is usually nothing left
        to close.

        If deregistering a region fails, which takes a device or driver error
        and is logged as an error, a transfer using it is not cancelled. It
        keeps waiting until the server replies or the connection fails, since
        the server could still reach the memory, and that memory is never
        released; see :attr:`RdmaRegion.memory_released`.
        """
        if _is_credential_provider_executing(self):
            raise RuntimeError(
                "Cannot close a client from its own credential provider callback"
            )
        with self._client_lock:
            if not self._is_closed:
                self._is_closed = True
                with self._pubsub_condition:
                    self._pubsub_condition.notify_all()
                core_client = getattr(self, "_core_client", self._ffi.NULL)
                if core_client != self._ffi.NULL:
                    self._core_client = self._ffi.NULL
                    if getattr(self, "_rdma_calls", 0) == 0:
                        self._lib.close_client(core_client)
                    else:
                        # Freeing the native client now could free it under an
                        # RDMA call on another thread. Cancel their transfers
                        # instead, and let the last call out free it.
                        self._deferred_core_client = core_client
                        # It keeps delivering pubsub messages and refreshing
                        # IAM tokens until it is freed, so its callbacks and
                        # the credential owner must outlive it.
                        self._deferred_callback_refs = (
                            self._pubsub_callback_ref,
                            self._credential_provider_callback_ref,
                        )
                        self._cancel_rdma(core_client)
                self._pubsub_callback_ref = None
                deferred = getattr(self, "_deferred_core_client", self._ffi.NULL)
                if deferred == self._ffi.NULL:
                    owner = getattr(self, "_credential_provider_callback_owner", None)
                    if owner is not None:
                        owner.close()
                    self._credential_provider_callback_owner = None
                self._credential_provider_callback_ref = None
        # Closing the client may be what lets the fabric go of memory it held.
        _RETAINED_RDMA_MEMORY.release_what_is_free()

    def _cancel_rdma(self, core_client) -> None:
        """
        Revoke every region the client registered, which cancels every
        transfer in flight on it, without freeing the native client.
        """
        error = self._lib.rdma_close_regions(core_client)
        if error != self._ffi.NULL:
            try:
                message = self._ffi.string(error).decode(ENCODING)
            finally:
                self._lib.free_c_string(error)
            Logger.log(
                Level.ERROR,
                "close",
                "could not revoke every RDMA region, so a transfer may still be "
                f"waiting: {message}",
            )

    def __enter__(self) -> Self:
        return self

    def __exit__(
        self,
        exc_type: Optional[type[BaseException]],
        exc: Optional[BaseException],
        tb: Optional[TracebackType],
    ) -> None:
        self.close()

    def scoped_connection(
        self, timeout: float = 5.0, routing_key: Optional[str] = None
    ) -> "IsolatedScope":
        """
        Acquire an isolated execution scope — a dedicated connection for operations
        requiring per-connection state (WATCH/MULTI/EXEC, CLIENT TRACKING, blocking
        commands).

        The scope bypasses the multiplexer, executing commands on its own TCP
        connection. Use as a context manager for automatic release:

            with client.scoped_connection(routing_key="my-key") as scope:
                scope.watch("my-key")
                val = scope.get("my-key")
                scope.multi()
                scope.set("my-key", str(int(val or "0") + 1))
                result = scope.exec()

        Args:
            timeout: Maximum seconds to wait for a scope connection (default 5.0).
            routing_key: In cluster mode, the key whose hash slot determines which
                node the scope connects to, and against which the scope's first
                keyed command is validated (a command for a different slot is
                rejected locally with CROSSSLOT). If None, the scope starts
                unconstrained (slot 0 selects only the initial connection target):
                the first keyed command may target any slot and pins the scope to
                it, after which later keyed commands for a different slot receive
                CROSSSLOT. In standalone mode this argument is ignored.

        Returns:
            An IsolatedScope instance.

        Raises:
            TimeoutError: If no scope is available within the timeout.
            ConnectionError: If the client is closed while waiting.
            RequestError: If the client's configuration cannot produce a
                scoped connection.
            ClosingError: If the client is already closed.
        """
        from .isolated_scope import IsolatedScope

        if self._is_closed:
            raise ClosingError("Client is closed.")

        # Use the pointer address as client_id for the scope pool
        client_id = int(self._ffi.cast("uintptr_t", self._core_client))
        conn_req_bytes = self._conn_req_bytes

        # Compute routing slot from key. Presence is carried separately so a
        # cluster scope with no routing key stays unconstrained (any primary)
        # rather than being pinned to slot 0, which is a real slot.
        has_routing_slot = routing_key is not None
        routing_slot = (
            _slot_for_key(routing_key.encode("utf-8")) if routing_key is not None else 0
        )

        buf = self._ffi.from_buffer(conn_req_bytes)
        result = self._lib.glide_scope_acquire_blocking(
            client_id,
            self._ffi.cast("const uint8_t*", buf),
            len(conn_req_bytes),
            has_routing_slot,
            routing_slot,
            # uint64_t on the FFI side: a negative value would raise OverflowError
            # instead of the documented TimeoutError. Negative means no wait.
            max(0, int(timeout * 1000)),
        )
        scope_id = handle_command_result(
            self._ffi, self._lib, result, lambda resp: resp.int_value
        )
        return IsolatedScope(
            scope_id,
            client_id,
            _SYNC_FFI,
            self._parse_scope_response,
        )

    def _parse_scope_response(self, response_ptr) -> Optional[str]:  # noqa: C901
        """Parse a CommandResponse pointer from a scope execution into a Python string."""
        if response_ptr == self._ffi.NULL:
            return None

        resp = response_ptr
        resp_type = resp.response_type

        # Null response
        if resp_type == 0:  # ResponseType::Null
            return None
        # Int
        elif resp_type == 1:  # ResponseType::Int
            return str(resp.int_value)
        # Float
        elif resp_type == 2:  # ResponseType::Float
            return str(resp.float_value)
        # Bool
        elif resp_type == 3:  # ResponseType::Bool
            return str(resp.bool_value)
        # String
        elif resp_type == 4:  # ResponseType::String
            if resp.string_value == self._ffi.NULL:
                return None
            return self._ffi.buffer(resp.string_value, resp.string_value_len)[:].decode(
                "utf-8"
            )
        # Array (for EXEC results, LRANGE, etc.)
        elif resp_type == 5:  # ResponseType::Array
            if resp.array_value == self._ffi.NULL or resp.array_value_len == 0:
                return None
            # For simple scope usage, return a string repr
            results = []
            for i in range(resp.array_value_len):
                elem = self._parse_scope_response(resp.array_value + i)
                results.append(elem)
            return str(results)
        # Ok
        elif resp_type == 8:  # ResponseType::Ok
            return "OK"
        # Error
        elif resp_type == 9:  # ResponseType::Error
            if resp.string_value != self._ffi.NULL:
                msg = self._ffi.string(resp.string_value).decode("utf-8")
                raise RuntimeError(f"Server error: {msg}")
            raise RuntimeError("Server error (unknown)")
        else:
            # Fallback for Map, Sets, etc.
            return None

closed property

Whether :meth:close has been called. A closed client refuses every later command, registration, and transfer, so a new client is needed. After a failed RDMA transfer this says whether the region can be registered again on this client; see :class:RdmaRegion.

Example

client.close() client.closed True

try_get_pubsub_message()

Try to get a pubsub message without blocking

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
def try_get_pubsub_message(self) -> Optional[PubSubMsg]:
    """Try to get a pubsub message without blocking"""
    if self._is_closed:
        raise ClosingError(
            "Unable to execute requests; the client is closed. Please create a new client."
        )

    if self._config._get_pubsub_callback_and_context()[0] is not None:
        raise ConfigurationError(
            "The operation will never succeed since messages will be passed to the configured callback."
        )

    with self._pubsub_condition:
        if self._pubsub_queue:
            return self._pubsub_queue.pop(0)
        else:
            return None

get_pubsub_message()

Get a pubsub message, blocking until one is available

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
def get_pubsub_message(self) -> PubSubMsg:
    """Get a pubsub message, blocking until one is available"""
    if self._is_closed:
        raise ClosingError(
            "Unable to execute requests; the client is closed. Please create a new client."
        )

    if self._config._get_pubsub_callback_and_context()[0] is not None:
        raise ConfigurationError(
            "The operation will never complete since messages will be passed to the configured callback."
        )

    with self._pubsub_condition:
        while not self._pubsub_queue:
            if self._is_closed:
                raise ClosingError("Client was closed while waiting for message")

            # Block indefinitely until notify() is called
            self._pubsub_condition.wait()

        return self._pubsub_queue.pop(0)

get_statistics()

Get compression and connection statistics for this client.

Returns:

Name Type Description
dict dict

A dictionary containing statistics with integer values: - total_connections: Total number of connections - total_clients: Total number of clients - total_values_compressed: Number of values successfully compressed - total_values_decompressed: Number of values successfully decompressed - total_original_bytes: Total bytes of original data before compression - total_bytes_compressed: Total bytes after compression - total_bytes_decompressed: Total bytes after decompression - compression_skipped_count: Number of times compression was skipped - subscription_out_of_sync_count: Failed reconciliation attempts - subscription_last_sync_timestamp: Last successful sync (milliseconds since epoch)

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
def get_statistics(self) -> dict:
    """
    Get compression and connection statistics for this client.

    Returns:
        dict: A dictionary containing statistics with integer values:
            - total_connections: Total number of connections
            - total_clients: Total number of clients
            - total_values_compressed: Number of values successfully compressed
            - total_values_decompressed: Number of values successfully decompressed
            - total_original_bytes: Total bytes of original data before compression
            - total_bytes_compressed: Total bytes after compression
            - total_bytes_decompressed: Total bytes after decompression
            - compression_skipped_count: Number of times compression was skipped
            - subscription_out_of_sync_count: Failed reconciliation attempts
            - subscription_last_sync_timestamp: Last successful sync (milliseconds since epoch)
    """
    # Call the C FFI get_statistics function (returns by value, no manual free needed)
    stats = self._lib.get_statistics()

    # Access the struct fields and convert to a dictionary
    return {
        "total_connections": stats.total_connections,
        "total_clients": stats.total_clients,
        "total_values_compressed": stats.total_values_compressed,
        "total_values_decompressed": stats.total_values_decompressed,
        "total_original_bytes": stats.total_original_bytes,
        "total_bytes_compressed": stats.total_bytes_compressed,
        "total_bytes_decompressed": stats.total_bytes_decompressed,
        "compression_skipped_count": stats.compression_skipped_count,
        "subscription_out_of_sync_count": stats.subscription_out_of_sync_count,
        "subscription_last_sync_timestamp": stats.subscription_last_sync_timestamp,
    }

get_subscriptions()

Get subscription state (desired vs actual).

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
1594
1595
1596
1597
1598
1599
def get_subscriptions(self):
    """Get subscription state (desired vs actual)."""
    result = self._execute_command(RequestType.GetSubscriptions, [])
    return self._parse_pubsub_state(
        result, is_cluster=isinstance(self, GlideClusterClient)
    )

rdma_available() staticmethod

Whether this build of GLIDE has RDMA compiled in.

A build from source without the RDMA feature returns false.

This says nothing about whether libfabric is on the machine. For whether RDMA can actually happen here, use :meth:rdma_usable.

Returns:

Name Type Description
bool bool

True if RDMA support is present in this build.

Example

BaseClient.rdma_available() True

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
@staticmethod
def rdma_available() -> bool:
    """
    Whether this build of GLIDE has RDMA compiled in.

    A build from source without the RDMA feature returns false.

    This says nothing about whether libfabric is on the machine.
    For whether RDMA can actually happen here, use :meth:`rdma_usable`.

    Returns:
        bool: True if RDMA support is present in this build.

    Example:
        >>> BaseClient.rdma_available()
        True
    """
    return bool(_SYNC_FFI.lib.rdma_available())

rdma_usable() staticmethod

Whether this build has RDMA support and can load a compatible libfabric on this machine.

It does not look for fabric hardware, so creating an RDMA client can still fail, for example with RdmaProvider.EfaDirect() on a machine without an EFA device.

Returns:

Name Type Description
bool bool

True if libfabric loads and this build supports RDMA.

Example

BaseClient.rdma_usable() False

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
@staticmethod
def rdma_usable() -> bool:
    """
    Whether this build has RDMA support and can load a compatible libfabric
    on this machine.

    It does not look for fabric hardware, so creating an RDMA client can
    still fail, for example with ``RdmaProvider.EfaDirect()`` on a machine
    without an EFA device.

    Returns:
        bool: True if libfabric loads and this build supports RDMA.

    Example:
        >>> BaseClient.rdma_usable()
        False
    """
    return bool(_SYNC_FFI.lib.rdma_usable())

register_rdma_region(memory)

Register memory so the server can transfer into or out of it directly.

The memory stays the caller's. Anything supporting the writable buffer protocol works: a bytearray, an mmap, a NumPy array, a tensor's backing store. It must not be resized or freed until the returned region is closed.

Register one large region and address windows of it per transfer rather than registering per operation.

Memory that GLIDE still holds from a closed region, which :attr:RdmaRegion.memory_released reports, is refused, because a write from that region's last transfer could still land in it. That includes any other view or slice of the same bytes. On efa-direct this happens only after a failed deregistration.

Parameters:

Name Type Description Default
memory Any

A writable, C-contiguous buffer to register.

required

Returns:

Name Type Description
RdmaRegion RdmaRegion

The registered region. Close when done with it.

Raises:

Type Description
RdmaError

If this build has no RDMA support, the client was not configured for RDMA, the memory is still held from a closed region, or the fabric refused the registration.

ClosingError

If the client is closed.

TypeError

If the buffer is not writable and C-contiguous.

Example

region = client.register_rdma_region(bytearray(1 << 20)) region.capacity 1048576

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
def register_rdma_region(self, memory: Any) -> RdmaRegion:
    """
    Register memory so the server can transfer into or out of it directly.

    The memory stays the caller's. Anything supporting the writable buffer
    protocol works: a ``bytearray``, an ``mmap``, a NumPy array, a tensor's
    backing store. It must not be resized or freed until the returned region
    is closed.

    Register one large region and address windows of it per transfer rather
    than registering per operation.

    Memory that GLIDE still holds from a closed region, which
    :attr:`RdmaRegion.memory_released` reports, is refused, because a write
    from that region's last transfer could still land in it. That includes
    any other view or slice of the same bytes. On efa-direct this happens
    only after a failed deregistration.

    Args:
        memory (Any): A writable, C-contiguous buffer to register.

    Returns:
        RdmaRegion: The registered region. Close when done with it.

    Raises:
        RdmaError: If this build has no RDMA support, the client was not
            configured for RDMA, the memory is still held from a closed
            region, or the fabric refused the registration.
        ClosingError: If the client is closed.
        TypeError: If the buffer is not writable and C-contiguous.

    Example:
        >>> region = client.register_rdma_region(bytearray(1 << 20))
        >>> region.capacity
        1048576
    """
    view = memoryview(memory)
    if view.readonly:
        raise TypeError("memory must be writable")
    if not view.c_contiguous:
        raise TypeError("memory must be C-contiguous")
    span = _memory_span(view)
    if _RETAINED_RDMA_MEMORY.overlaps(span):
        raise RdmaError(
            "this memory belongs to a closed RDMA region whose last transfer "
            "could still write into it; register different memory"
        )

    client_adapter_ptr = self._begin_rdma_call()
    buffer = self._ffi.from_buffer(view)
    try:
        registration = self._lib.register_rdma_region(
            client_adapter_ptr, buffer, view.nbytes
        )
        if registration == self._ffi.NULL:
            raise RdmaError(
                "Internal error: received NULL from register_rdma_region"
            )
        try:
            if registration.error_message != self._ffi.NULL:
                raise RdmaError(
                    self._ffi.string(registration.error_message).decode(ENCODING)
                )
            region = registration.region
            try:
                return RdmaRegion(self, memory, region)
            except BaseException:
                # Until the RdmaRegion is built, nothing else will free the
                # region, so free it here instead of leaking its pinned pages.
                _free_rdma_region(
                    self._lib, self._ffi, region, memory, buffer, span
                )
                raise
        finally:
            self._lib.free_rdma_registration(registration)
    except BaseException:
        # The error's traceback keeps this frame alive, and with it `view`.
        # If the error ends up in a reference cycle, Python 3.9's garbage
        # collector crashes freeing a memoryview that `buffer` still holds
        # an export on, so let go of the export before the error leaves.
        del buffer
        raise
    finally:
        self._end_rdma_call()

rdma_get(key, window)

Read a value directly into a window of registered memory.

Waits until the transfer completes. The bytes are in the window by the time this returns. The value never travels in the RESP reply.

There is no timeout. The server moves the payload with a remote memory operation that nothing can call off once it is posted, so giving up early would leave the server writing into the window while the caller believed it was free.

To cancel a transfer, call :meth:close on the client from another thread. That first cuts the server off from every region the client registered, then this call returns raising ClosingError, unless the server's reply was already arriving, in which case it returns as usual. Bytes that landed before the close stay, so the window then holds an unknown mix of old and new bytes. See :meth:close for the rare case where the close cannot cancel the transfer.

A transfer that ends before the server is known to be done with the memory closes the region, for example one cancelled that way or one whose connection was lost. See :class:RdmaRegion for every case and how to recover.

Parameters:

Name Type Description Default
key TEncodable

The key to read.

required
window RdmaWindow

Where the value should land, from :meth:RdmaRegion.window. The server is told the window's length and refuses a larger value before writing anything, so the bytes around the window are never touched.

required

Returns:

Type Description
Optional[RdmaReadReceipt]

Optional[RdmaReadReceipt]: What the server transferred, or None if the

Optional[RdmaReadReceipt]

key does not exist. The landed bytes have already been verified

Optional[RdmaReadReceipt]

against the receipt's checksum.

Raises:

Type Description
RdmaError

If the region is closed, in use by another transfer, or belongs to another client; a MULTI is open on this client; the value was larger than the window (the region stays usable); the landed bytes did not match the checksum; or the server refused the transfer or its handshake.

ConnectionError

If the connection failed, or has to be replaced because its handshake left it unusable. Check region.closed: the region stays open when the transfer was never sent.

ClosingError

If the client is closed, including when it is closed during the transfer to cancel it.

TypeError

If window is not an RdmaWindow.

Example

receipt = client.rdma_get(b"key", region.window(4096, 4096)) receipt.bytes_written if receipt else "missing"

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
def rdma_get(
    self,
    key: TEncodable,
    window: RdmaWindow,
) -> Optional[RdmaReadReceipt]:
    """
    Read a value directly into a window of registered memory.

    Waits until the transfer completes. The bytes are in the window by the
    time this returns. The value never travels in the RESP reply.

    There is no timeout. The server moves the payload with a remote memory
    operation that nothing can call off once it is posted, so giving up
    early would leave the server writing into the window while the caller
    believed it was free.

    To cancel a transfer, call :meth:`close` on the client from another
    thread. That first cuts the server off from every region the client
    registered, then this call returns raising ``ClosingError``, unless
    the server's reply was already arriving, in which case it returns as
    usual. Bytes that landed before the close stay, so the window then
    holds an unknown mix of old and new bytes. See :meth:`close` for the
    rare case where the close cannot cancel the transfer.

    A transfer that ends before the server is known to be done with the
    memory closes the region, for example one cancelled that way or one
    whose connection was lost. See :class:`RdmaRegion` for every case and
    how to recover.

    Args:
        key (TEncodable): The key to read.
        window (RdmaWindow): Where the value should land, from
            :meth:`RdmaRegion.window`. The server is told the window's
            length and refuses a larger value before writing anything, so
            the bytes around the window are never touched.

    Returns:
        Optional[RdmaReadReceipt]: What the server transferred, or None if the
        key does not exist. The landed bytes have already been verified
        against the receipt's ``checksum``.

    Raises:
        RdmaError: If the region is closed, in use by another transfer, or
            belongs to another client; a ``MULTI`` is open on this client;
            the value was larger than the window (the region stays usable);
            the landed bytes did not match the checksum; or the server
            refused the transfer or its handshake.
        ConnectionError: If the connection failed, or has to be replaced
            because its handshake left it unusable. Check
            ``region.closed``: the region stays open when the transfer was
            never sent.
        ClosingError: If the client is closed, including when it is closed
            during the transfer to cancel it.
        TypeError: If ``window`` is not an ``RdmaWindow``.

    Example:
        >>> receipt = client.rdma_get(b"key", region.window(4096, 4096))
        >>> receipt.bytes_written if receipt else "missing"
    """
    c_key = self._to_c_key(key)
    return self._rdma_transfer(
        window,
        lambda client, region: self._lib.rdma_get(
            client, *c_key, region, window.offset, window.length
        ),
    )

rdma_set(key, window, checksum=RdmaSetChecksum.Skip())

Store a value the server reads directly out of a window of registered memory.

As with rdma_get, there is no timeout, closing the client from another thread cancels the call, raising ClosingError, and a transfer that ends before the server is known to be done with the memory closes the region. See :class:RdmaRegion for how to recover.

Parameters:

Name Type Description Default
key TEncodable

The key to write.

required
window RdmaWindow

The bytes to send, from :meth:RdmaRegion.window.

required
checksum Union[Skip, Compute, Known]

Whether the server checks the bytes it read against a CRC-32c before storing them; see :class:RdmaSetChecksum. Defaults to RdmaSetChecksum.Skip(), which sends none.

Skip()

Returns:

Type Description
None

None. The server acknowledges without reporting a length, having

None

read exactly the number of bytes the command named. A short read

None

fails the transfer and raises instead.

Raises:

Type Description
RdmaError

If the region is closed, in use by another transfer, or belongs to another client; a MULTI is open on this client; or the server refused the write or its handshake, including when the bytes it read do not match the checksum. A refused write stores nothing and leaves the region usable. If the region closed instead, the outcome is unknown: for example, a write the server queued inside another thread's MULTI may still be stored on EXEC.

ConnectionError

As for rdma_get.

ClosingError

If the client is closed, including when it is closed during the transfer to cancel it.

TypeError

If window is not an RdmaWindow, or checksum is not an RdmaSetChecksum choice.

ValueError

If a known checksum is not an unsigned 32-bit integer.

Example

window = region.window(0, 11) window.memoryview()[:] = b"hello world" client.rdma_set(b"key", window, checksum=RdmaSetChecksum.Compute())

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
def rdma_set(
    self,
    key: TEncodable,
    window: RdmaWindow,
    checksum: Union[
        RdmaSetChecksum.Skip, RdmaSetChecksum.Compute, RdmaSetChecksum.Known
    ] = RdmaSetChecksum.Skip(),
) -> None:
    """
    Store a value the server reads directly out of a window of registered
    memory.

    As with ``rdma_get``, there is no timeout, closing the client from
    another thread cancels the call, raising ``ClosingError``, and a
    transfer that ends before the server is known to be done with the
    memory closes the region. See :class:`RdmaRegion` for how to recover.

    Args:
        key (TEncodable): The key to write.
        window (RdmaWindow): The bytes to send, from
            :meth:`RdmaRegion.window`.
        checksum: Whether the server checks the bytes it read against a
            CRC-32c before storing them; see :class:`RdmaSetChecksum`.
            Defaults to ``RdmaSetChecksum.Skip()``, which sends none.

    Returns:
        None. The server acknowledges without reporting a length, having
        read exactly the number of bytes the command named. A short read
        fails the transfer and raises instead.

    Raises:
        RdmaError: If the region is closed, in use by another transfer, or
            belongs to another client; a ``MULTI`` is open on this client;
            or the server refused the write or its handshake, including when
            the bytes it read do not match the checksum. A refused write
            stores nothing and leaves the region usable. If the region
            closed instead, the outcome is unknown: for example, a write
            the server queued inside another thread's ``MULTI`` may still
            be stored on ``EXEC``.
        ConnectionError: As for ``rdma_get``.
        ClosingError: If the client is closed, including when it is closed
            during the transfer to cancel it.
        TypeError: If ``window`` is not an ``RdmaWindow``, or ``checksum``
            is not an ``RdmaSetChecksum`` choice.
        ValueError: If a known checksum is not an unsigned 32-bit integer.

    Example:
        >>> window = region.window(0, 11)
        >>> window.memoryview()[:] = b"hello world"
        >>> client.rdma_set(b"key", window, checksum=RdmaSetChecksum.Compute())
    """
    checksum_mode, checksum_value = self._rdma_set_checksum(checksum)
    c_key = self._to_c_key(key)
    self._rdma_transfer(
        window,
        lambda client, region: self._lib.rdma_set(
            client,
            *c_key,
            region,
            window.offset,
            window.length,
            checksum_mode,
            checksum_value,
        ),
    )

rdma_checksum(data) staticmethod

CRC-32c of data, the integrity check the RDMA protocol carries.

The same value the server computes, so a caller can verify what landed after a read, or compute one before sending to pass to rdma_set as RdmaSetChecksum.Known. rdma_get verifies every read against the checksum the server sends with its reply.

Parameters:

Name Type Description Default
data Any

Any bytes-like object.

required

Returns:

Name Type Description
int int

The CRC-32c, as an unsigned 32-bit integer.

Raises:

Type Description
RdmaError

If this build has no RDMA support.

Example

GlideClient.rdma_checksum(b"123456789") 3808858755

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
@staticmethod
def rdma_checksum(data: Any) -> int:
    """
    CRC-32c of ``data``, the integrity check the RDMA protocol carries.

    The same value the server computes, so a caller can verify what landed
    after a read, or compute one before sending to pass to ``rdma_set`` as
    ``RdmaSetChecksum.Known``. ``rdma_get`` verifies every read against the
    checksum the server sends with its reply.

    Args:
        data (Any): Any bytes-like object.

    Returns:
        int: The CRC-32c, as an unsigned 32-bit integer.

    Raises:
        RdmaError: If this build has no RDMA support.

    Example:
        >>> GlideClient.rdma_checksum(b"123456789")
        3808858755
    """
    ffi, lib = _SYNC_FFI.ffi, _SYNC_FFI.lib
    # Check before `view` and `buffer` exist. An error raised while `buffer`
    # holds an export on `view` keeps both alive in its traceback, and
    # Python 3.9's garbage collector crashes if that error ends up in a
    # reference cycle.
    if not lib.rdma_available():
        raise RdmaError(
            "this build of GLIDE has no RDMA support compiled in, so it "
            "cannot compute a transfer checksum"
        )
    view = memoryview(data)
    out = ffi.new("uint32_t*")
    buffer = ffi.from_buffer(view) if view.nbytes else ffi.NULL
    if not lib.rdma_checksum(buffer, view.nbytes, out):
        raise RdmaError("Internal error: rdma_checksum failed")
    return int(out[0])

close()

Close the client. Closing twice is a no-op.

With RDMA, this also cancels every transfer in flight on another thread: it cuts the server off from every region the client registered, and each blocked rdma_get or rdma_set then raises ClosingError, unless its reply was already arriving, in which case it returns as usual.

This returns without waiting for those calls. Close a region only after every transfer call using it has returned; while one is still running, :meth:RdmaRegion.close raises RdmaError. A cancelled transfer closes its own region on the way out, so there is usually nothing left to close.

If deregistering a region fails, which takes a device or driver error and is logged as an error, a transfer using it is not cancelled. It keeps waiting until the server replies or the connection fails, since the server could still reach the memory, and that memory is never released; see :attr:RdmaRegion.memory_released.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
def close(self) -> None:
    """
    Close the client. Closing twice is a no-op.

    With RDMA, this also cancels every transfer in flight on another thread:
    it cuts the server off from every region the client registered, and
    each blocked ``rdma_get`` or ``rdma_set`` then raises ``ClosingError``,
    unless its reply was already arriving, in which case it returns as
    usual.

    This returns without waiting for those calls. Close a region only after
    every transfer call using it has returned; while one is still running,
    :meth:`RdmaRegion.close` raises ``RdmaError``. A cancelled transfer
    closes its own region on the way out, so there is usually nothing left
    to close.

    If deregistering a region fails, which takes a device or driver error
    and is logged as an error, a transfer using it is not cancelled. It
    keeps waiting until the server replies or the connection fails, since
    the server could still reach the memory, and that memory is never
    released; see :attr:`RdmaRegion.memory_released`.
    """
    if _is_credential_provider_executing(self):
        raise RuntimeError(
            "Cannot close a client from its own credential provider callback"
        )
    with self._client_lock:
        if not self._is_closed:
            self._is_closed = True
            with self._pubsub_condition:
                self._pubsub_condition.notify_all()
            core_client = getattr(self, "_core_client", self._ffi.NULL)
            if core_client != self._ffi.NULL:
                self._core_client = self._ffi.NULL
                if getattr(self, "_rdma_calls", 0) == 0:
                    self._lib.close_client(core_client)
                else:
                    # Freeing the native client now could free it under an
                    # RDMA call on another thread. Cancel their transfers
                    # instead, and let the last call out free it.
                    self._deferred_core_client = core_client
                    # It keeps delivering pubsub messages and refreshing
                    # IAM tokens until it is freed, so its callbacks and
                    # the credential owner must outlive it.
                    self._deferred_callback_refs = (
                        self._pubsub_callback_ref,
                        self._credential_provider_callback_ref,
                    )
                    self._cancel_rdma(core_client)
            self._pubsub_callback_ref = None
            deferred = getattr(self, "_deferred_core_client", self._ffi.NULL)
            if deferred == self._ffi.NULL:
                owner = getattr(self, "_credential_provider_callback_owner", None)
                if owner is not None:
                    owner.close()
                self._credential_provider_callback_owner = None
            self._credential_provider_callback_ref = None
    # Closing the client may be what lets the fabric go of memory it held.
    _RETAINED_RDMA_MEMORY.release_what_is_free()

scoped_connection(timeout=5.0, routing_key=None)

Acquire an isolated execution scope — a dedicated connection for operations requiring per-connection state (WATCH/MULTI/EXEC, CLIENT TRACKING, blocking commands).

The scope bypasses the multiplexer, executing commands on its own TCP connection. Use as a context manager for automatic release:

with client.scoped_connection(routing_key="my-key") as scope:
    scope.watch("my-key")
    val = scope.get("my-key")
    scope.multi()
    scope.set("my-key", str(int(val or "0") + 1))
    result = scope.exec()

Parameters:

Name Type Description Default
timeout float

Maximum seconds to wait for a scope connection (default 5.0).

5.0
routing_key Optional[str]

In cluster mode, the key whose hash slot determines which node the scope connects to, and against which the scope's first keyed command is validated (a command for a different slot is rejected locally with CROSSSLOT). If None, the scope starts unconstrained (slot 0 selects only the initial connection target): the first keyed command may target any slot and pins the scope to it, after which later keyed commands for a different slot receive CROSSSLOT. In standalone mode this argument is ignored.

None

Returns:

Type Description
IsolatedScope

An IsolatedScope instance.

Raises:

Type Description
TimeoutError

If no scope is available within the timeout.

ConnectionError

If the client is closed while waiting.

RequestError

If the client's configuration cannot produce a scoped connection.

ClosingError

If the client is already closed.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
def scoped_connection(
    self, timeout: float = 5.0, routing_key: Optional[str] = None
) -> "IsolatedScope":
    """
    Acquire an isolated execution scope — a dedicated connection for operations
    requiring per-connection state (WATCH/MULTI/EXEC, CLIENT TRACKING, blocking
    commands).

    The scope bypasses the multiplexer, executing commands on its own TCP
    connection. Use as a context manager for automatic release:

        with client.scoped_connection(routing_key="my-key") as scope:
            scope.watch("my-key")
            val = scope.get("my-key")
            scope.multi()
            scope.set("my-key", str(int(val or "0") + 1))
            result = scope.exec()

    Args:
        timeout: Maximum seconds to wait for a scope connection (default 5.0).
        routing_key: In cluster mode, the key whose hash slot determines which
            node the scope connects to, and against which the scope's first
            keyed command is validated (a command for a different slot is
            rejected locally with CROSSSLOT). If None, the scope starts
            unconstrained (slot 0 selects only the initial connection target):
            the first keyed command may target any slot and pins the scope to
            it, after which later keyed commands for a different slot receive
            CROSSSLOT. In standalone mode this argument is ignored.

    Returns:
        An IsolatedScope instance.

    Raises:
        TimeoutError: If no scope is available within the timeout.
        ConnectionError: If the client is closed while waiting.
        RequestError: If the client's configuration cannot produce a
            scoped connection.
        ClosingError: If the client is already closed.
    """
    from .isolated_scope import IsolatedScope

    if self._is_closed:
        raise ClosingError("Client is closed.")

    # Use the pointer address as client_id for the scope pool
    client_id = int(self._ffi.cast("uintptr_t", self._core_client))
    conn_req_bytes = self._conn_req_bytes

    # Compute routing slot from key. Presence is carried separately so a
    # cluster scope with no routing key stays unconstrained (any primary)
    # rather than being pinned to slot 0, which is a real slot.
    has_routing_slot = routing_key is not None
    routing_slot = (
        _slot_for_key(routing_key.encode("utf-8")) if routing_key is not None else 0
    )

    buf = self._ffi.from_buffer(conn_req_bytes)
    result = self._lib.glide_scope_acquire_blocking(
        client_id,
        self._ffi.cast("const uint8_t*", buf),
        len(conn_req_bytes),
        has_routing_slot,
        routing_slot,
        # uint64_t on the FFI side: a negative value would raise OverflowError
        # instead of the documented TimeoutError. Negative means no wait.
        max(0, int(timeout * 1000)),
    )
    scope_id = handle_command_result(
        self._ffi, self._lib, result, lambda resp: resp.int_value
    )
    return IsolatedScope(
        scope_id,
        client_id,
        _SYNC_FFI,
        self._parse_scope_response,
    )

GlideClusterClient

Bases: BaseClient, ClusterCommands

Client used for connection to cluster servers. For full documentation, see https://glide.valkey.io/how-to/client-initialization/#cluster

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
class GlideClusterClient(BaseClient, ClusterCommands):
    """
    Client used for connection to cluster servers.
    For full documentation, see
    https://glide.valkey.io/how-to/client-initialization/#cluster
    """

    def _build_cluster_scan_args(self, match, count, type, allow_non_covered_slots):
        args = []
        if match is not None:
            # Inline _encode_arg logic
            if isinstance(match, str):
                encoded_match = match.encode(ENCODING)
            else:
                encoded_match = match
            args.extend([b"MATCH", encoded_match])

        if count is not None:
            args.extend([b"COUNT", str(count).encode(ENCODING)])
        if type is not None:
            args.extend([b"TYPE", type.value.encode(ENCODING)])
        if allow_non_covered_slots:
            args.extend([b"ALLOW_NON_COVERED_SLOTS"])

        return args

    def _cluster_scan(
        self,
        cursor: ClusterScanCursor,
        match: Optional[TEncodable] = None,
        count: Optional[int] = None,
        type: Optional[ObjectType] = None,
        allow_non_covered_slots: bool = False,
    ) -> List[Union[ClusterScanCursor, List[bytes]]]:
        if self._is_closed:
            raise ClosingError(
                "Unable to execute requests; the client is closed. Please create a new client."
            )

        client_adapter_ptr = self._core_client
        if client_adapter_ptr == self._ffi.NULL:
            raise ValueError("Invalid client pointer.")

        # Use helper method to build args
        args = self._build_cluster_scan_args(
            match, count, type, allow_non_covered_slots
        )
        # Convert cursor to C string
        cursor_string = cursor.get_cursor()
        cursor_bytes = cursor_string.encode(ENCODING) + b"\0"  # Null terminate for C

        # Keep references to prevent GC
        temp_buffers: List[Any] = [cursor_bytes]
        cursor_buffer = self._ffi.from_buffer(cursor_bytes)

        # Prepare FFI arguments
        if args:
            args_array, args_len_array, arg_buffers = self._to_c_strings(args)
            temp_buffers.extend(arg_buffers)  # Keep references alive
            arg_count = len(args)
        else:
            args_array = self._ffi.NULL
            args_len_array = self._ffi.NULL
            arg_count = 0

        result_ptr = self._lib.request_cluster_scan(
            client_adapter_ptr,
            0,
            cursor_buffer,
            arg_count,
            args_array,
            args_len_array,
        )

        response_data = self._handle_cmd_result(result_ptr)

        if not isinstance(response_data, list) or len(response_data) != 2:
            raise RequestError("Unexpected cluster scan response format")

        new_cursor = response_data[0]
        if isinstance(new_cursor, bytes):
            new_cursor = new_cursor.decode(ENCODING)

        keys_list = response_data[1] if response_data[1] is not None else []

        return [ClusterScanCursor(new_cursor), keys_list]

GlideClient

Bases: BaseClient, StandaloneCommands

Client used for connection to standalone servers. For full documentation, see https://glide.valkey.io/how-to/client-initialization/#standalone

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/glide_client.py
2430
2431
2432
2433
2434
2435
2436
2437
class GlideClient(BaseClient, StandaloneCommands):
    """
    Client used for connection to standalone servers.
    For full documentation, see
    https://glide.valkey.io/how-to/client-initialization/#standalone
    """

    pass