Skip to content

glide_sync

ClientPool

Client-instance pool backed by the Rust core.

The Rust pool owns client lifecycle (creation, bounded size). This Python class provides: - acquire-with-timeout retry loop (exponential backoff) - Cached GlideClient wrappers (one per client_id, reused across borrows) - Zero-overhead borrow() context manager

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/client_pool.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
class ClientPool:
    """
    Client-instance pool backed by the Rust core.

    The Rust pool owns client lifecycle (creation, bounded size).
    This Python class provides:
    - acquire-with-timeout retry loop (exponential backoff)
    - Cached GlideClient wrappers (one per client_id, reused across borrows)
    - Zero-overhead borrow() context manager
    """

    __slots__ = (
        "_ffi",
        "_lib",
        "_client_config",
        "_pool_config",
        "_closed",
        "_client_cache",
        "_conn_req_bytes",
        "_pool_id",
        "_cache_lock",
    )

    @classmethod
    def create(
        cls,
        client_config: BaseClientConfiguration,
        pool_config: Optional[PoolConfig] = None,
    ) -> "ClientPool":
        """Create a pool and validate connectivity with a probe client.

        Creates the pool infrastructure, then attempts to connect a single
        probe client using the same config. If the probe fails, the pool is
        destroyed and the actual connection error is propagated (not a timeout).

        Args:
            client_config: Client configuration (standalone or cluster).
            pool_config: Optional pool sizing/timeout configuration.

        Returns:
            A ready-to-use ClientPool instance.

        Raises:
            The same exception that GlideClient.create() would raise on
            connection failure.
        """
        pool = cls(client_config, pool_config)
        try:
            probe = GlideClient.create(client_config)
            probe.close()
        except Exception:
            pool.close()
            raise
        return pool

    def __init__(
        self,
        client_config: BaseClientConfiguration,
        pool_config: Optional[PoolConfig] = None,
    ):
        # Custom providers are direct-client-only; pools may use the default AWS chain.
        credentials = getattr(client_config, "credentials", None)
        iam_config = getattr(credentials, "iam_config", None)
        if iam_config is not None and iam_config.credential_provider is not None:
            raise ValueError(
                "Pool clients cannot use a custom IAM credentials provider. "
                "Configure IAM without a credential_provider to use the default AWS credential chain."
            )

        # Reject pubsub subscriptions — pool state reset doesn't UNSUBSCRIBE
        if (
            hasattr(client_config, "pubsub_subscriptions")
            and client_config.pubsub_subscriptions
        ):
            raise ValueError(
                "Pool clients cannot have pubsub subscriptions configured. "
                "Use the main client's pubsub API for subscriptions."
            )

        # TODO: support RDMA in pools.
        if getattr(client_config, "rdma", None) is not None:
            raise ValueError(
                "Pool clients cannot have RDMA configured. "
                "Use a client outside a pool for RDMA transfers."
            )

        ffi_instance = _GlideFFI()
        self._ffi = ffi_instance.ffi
        self._lib = ffi_instance.lib
        self._client_config = client_config
        self._pool_config = pool_config or PoolConfig()
        self._closed = False
        self._client_cache: dict = {}
        # Lock for _client_cache under free-threading (concurrent get_or_create_client)
        self._cache_lock = threading.Lock()

        # Serialize the connection request protobuf. Route through the shared
        # helper so pooled clients honour lib_name / client_info_tag exactly
        # like direct GlideClient.create() clients do.
        conn_req = _create_sync_connection_request(client_config)
        self._conn_req_bytes = conn_req.SerializeToString()

        # Create the Rust pool via FFI (SyncClient type)
        client_type = self._ffi.new("ClientType*")
        client_type._type = 1  # Sync = 1 (from ClientTypeEnum)
        pool_id = self._lib.glide_pool_create(
            self._pool_config.max_size,
            self._pool_config.min_idle,
            self._pool_config.idle_timeout_ms,
            self._pool_config.request_timeout_ms,
            self._pool_config.abandon_timeout_ms,
            self._conn_req_bytes,
            len(self._conn_req_bytes),
            client_type,
        )

        if pool_id == -1:
            raise ValueError("Invalid pool configuration")
        if pool_id < 0:
            raise RuntimeError(f"Failed to create pool (error code: {pool_id})")

        self._pool_id = pool_id

    @property
    def pool_id(self) -> int:
        return self._pool_id

    @property
    def is_closed(self) -> bool:
        return self._closed

    def acquire(self, timeout: Optional[float] = None) -> int:
        """
        Acquire a client_id from the Rust pool.

        Blocks in Rust using a condvar until a client is available or timeout.
        Single FFI call — no polling loop.

        Returns:
            client_id (positive integer) for use with borrow() or get_client().

        Raises:
            TimeoutError: If no client available within timeout.
            RuntimeError: If pool is closed or invalid.
        """
        if self._closed:
            raise RuntimeError("Pool is closed")

        timeout = (
            timeout if timeout is not None else self._pool_config.acquire_timeout_s
        )
        timeout_ms = int(timeout * 1000)

        client_id = self._lib.glide_pool_acquire_blocking(self._pool_id, timeout_ms)

        if client_id >= 0:
            return client_id
        if client_id == -2:
            raise RuntimeError("Invalid pool_id — pool was destroyed")

        raise TimeoutError(
            f"Pool exhausted: could not acquire client within {timeout}s"
        )

    def release(self, client_id: int) -> None:
        """Release a borrowed client back to the pool."""
        self._lib.glide_pool_release(self._pool_id, client_id)

    def borrow(self, timeout: Optional[float] = None):
        """
        Returns a context manager that acquires a client from the Rust pool.

        The returned client dispatches commands through the native ClientAdapter
        managed by the Rust pool. On exit, the client is released back to the pool.

        Usage:
            with pool.borrow() as client:
                client.set("key", "value")
                result = client.get("key")
        """
        return _BorrowContext(self, timeout)

    def _get_or_create_client(self, client_id: int) -> BaseClient:
        """
        Get a usable GlideClient wrapper for the given client_id.

        On first borrow of a client_id, creates a thin wrapper pointing to the
        Rust-managed ClientAdapter. Subsequent borrows of the same client_id
        reuse the cached wrapper (zero allocation).
        """
        cached = self._client_cache.get(client_id)
        if cached is not None:
            return cached

        with self._cache_lock:
            # Double-check after acquiring lock
            cached = self._client_cache.get(client_id)
            if cached is not None:
                return cached

            # Get the native ClientAdapter pointer from the Rust pool
            adapter_ptr = self._lib.glide_pool_get_client_ptr(client_id)
            if adapter_ptr == 0:
                raise RuntimeError(
                    f"Pool client_id {client_id} has no associated ClientAdapter"
                )

            # Create a GlideClient shell pointing to the pooled adapter.
            cast_ptr = self._ffi.cast("void*", adapter_ptr)

            client = GlideClient.__new__(GlideClient)  # type: ignore[type-abstract]
            client._ffi = self._ffi
            client._lib = self._lib
            client._config = self._client_config
            client._is_closed = False
            client._pubsub_queue = []
            client._pubsub_lock = threading.Lock()
            client._pubsub_condition = threading.Condition(client._pubsub_lock)
            client._pubsub_callback_ref = None
            client._client_lock = threading.Lock()
            client._core_client = cast_ptr
            client._conn_req_bytes = self._conn_req_bytes

            self._client_cache[client_id] = client
            return client

    def metrics(self) -> dict:
        """Get pool metrics: idle, active, total counts.

        Zeros when the pool was destroyed.
        """
        m = self._lib.glide_pool_metrics(self._pool_id)
        return {"idle": m.idle, "active": m.active, "total": m.total}

    @property
    def idle_count(self) -> int:
        return self.metrics()["idle"]

    @property
    def active_count(self) -> int:
        return self.metrics()["active"]

    @property
    def total_count(self) -> int:
        return self.metrics()["total"]

    def close(self) -> None:
        """Destroy the pool. All idle clients are closed."""
        if not self._closed:
            self._closed = True
            self._lib.glide_pool_destroy(self._pool_id)
            self._client_cache.clear()

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

    def __del__(self):
        # Do NOT call close() from __del__. The FFI glide_pool_destroy call
        # can race with active pubsub callbacks from the Rust side, causing
        # segfaults. Users must call close() explicitly or use context manager.
        pass

create(client_config, pool_config=None) classmethod

Create a pool and validate connectivity with a probe client.

Creates the pool infrastructure, then attempts to connect a single probe client using the same config. If the probe fails, the pool is destroyed and the actual connection error is propagated (not a timeout).

Parameters:

Name Type Description Default
client_config BaseClientConfiguration

Client configuration (standalone or cluster).

required
pool_config Optional[PoolConfig]

Optional pool sizing/timeout configuration.

None

Returns:

Type Description
ClientPool

A ready-to-use ClientPool instance.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/client_pool.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
@classmethod
def create(
    cls,
    client_config: BaseClientConfiguration,
    pool_config: Optional[PoolConfig] = None,
) -> "ClientPool":
    """Create a pool and validate connectivity with a probe client.

    Creates the pool infrastructure, then attempts to connect a single
    probe client using the same config. If the probe fails, the pool is
    destroyed and the actual connection error is propagated (not a timeout).

    Args:
        client_config: Client configuration (standalone or cluster).
        pool_config: Optional pool sizing/timeout configuration.

    Returns:
        A ready-to-use ClientPool instance.

    Raises:
        The same exception that GlideClient.create() would raise on
        connection failure.
    """
    pool = cls(client_config, pool_config)
    try:
        probe = GlideClient.create(client_config)
        probe.close()
    except Exception:
        pool.close()
        raise
    return pool

acquire(timeout=None)

Acquire a client_id from the Rust pool.

Blocks in Rust using a condvar until a client is available or timeout. Single FFI call — no polling loop.

Returns:

Type Description
int

client_id (positive integer) for use with borrow() or get_client().

Raises:

Type Description
TimeoutError

If no client available within timeout.

RuntimeError

If pool is closed or invalid.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/client_pool.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def acquire(self, timeout: Optional[float] = None) -> int:
    """
    Acquire a client_id from the Rust pool.

    Blocks in Rust using a condvar until a client is available or timeout.
    Single FFI call — no polling loop.

    Returns:
        client_id (positive integer) for use with borrow() or get_client().

    Raises:
        TimeoutError: If no client available within timeout.
        RuntimeError: If pool is closed or invalid.
    """
    if self._closed:
        raise RuntimeError("Pool is closed")

    timeout = (
        timeout if timeout is not None else self._pool_config.acquire_timeout_s
    )
    timeout_ms = int(timeout * 1000)

    client_id = self._lib.glide_pool_acquire_blocking(self._pool_id, timeout_ms)

    if client_id >= 0:
        return client_id
    if client_id == -2:
        raise RuntimeError("Invalid pool_id — pool was destroyed")

    raise TimeoutError(
        f"Pool exhausted: could not acquire client within {timeout}s"
    )

release(client_id)

Release a borrowed client back to the pool.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/client_pool.py
227
228
229
def release(self, client_id: int) -> None:
    """Release a borrowed client back to the pool."""
    self._lib.glide_pool_release(self._pool_id, client_id)

borrow(timeout=None)

Returns a context manager that acquires a client from the Rust pool.

The returned client dispatches commands through the native ClientAdapter managed by the Rust pool. On exit, the client is released back to the pool.

Usage

with pool.borrow() as client: client.set("key", "value") result = client.get("key")

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/client_pool.py
231
232
233
234
235
236
237
238
239
240
241
242
243
def borrow(self, timeout: Optional[float] = None):
    """
    Returns a context manager that acquires a client from the Rust pool.

    The returned client dispatches commands through the native ClientAdapter
    managed by the Rust pool. On exit, the client is released back to the pool.

    Usage:
        with pool.borrow() as client:
            client.set("key", "value")
            result = client.get("key")
    """
    return _BorrowContext(self, timeout)

metrics()

Get pool metrics: idle, active, total counts.

Zeros when the pool was destroyed.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/client_pool.py
289
290
291
292
293
294
295
def metrics(self) -> dict:
    """Get pool metrics: idle, active, total counts.

    Zeros when the pool was destroyed.
    """
    m = self._lib.glide_pool_metrics(self._pool_id)
    return {"idle": m.idle, "active": m.active, "total": m.total}

close()

Destroy the pool. All idle clients are closed.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/client_pool.py
309
310
311
312
313
314
def close(self) -> None:
    """Destroy the pool. All idle clients are closed."""
    if not self._closed:
        self._closed = True
        self._lib.glide_pool_destroy(self._pool_id)
        self._client_cache.clear()

PoolConfig dataclass

Configuration for the client-instance pool.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/client_pool.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
@dataclass
class PoolConfig:
    """Configuration for the client-instance pool."""

    max_size: int = 10
    """Maximum number of clients in the pool."""

    min_idle: int = 1
    """Minimum idle clients to pre-warm at creation."""

    idle_timeout_ms: int = 300_000
    """Evict idle clients after this duration (ms). Default: 5 minutes."""

    request_timeout_ms: int = 5_000
    """Request timeout for commands (ms)."""

    acquire_timeout_s: float = 5.0
    """Maximum time to wait when pool is exhausted (seconds)."""

    abandon_timeout_ms: int = 300_000
    """Maximum inactivity time for a borrowed client before the pool reclaims it (ms).
    The timer resets on every command sent. The abandon monitor skips clients
    executing blocking commands (BLPOP, XREAD BLOCK, etc.).
    Set to 0 to disable abandon detection. Default: 5 minutes."""

max_size = 10 class-attribute instance-attribute

Maximum number of clients in the pool.

min_idle = 1 class-attribute instance-attribute

Minimum idle clients to pre-warm at creation.

idle_timeout_ms = 300000 class-attribute instance-attribute

Evict idle clients after this duration (ms). Default: 5 minutes.

request_timeout_ms = 5000 class-attribute instance-attribute

Request timeout for commands (ms).

acquire_timeout_s = 5.0 class-attribute instance-attribute

Maximum time to wait when pool is exhausted (seconds).

abandon_timeout_ms = 300000 class-attribute instance-attribute

Maximum inactivity time for a borrowed client before the pool reclaims it (ms). The timer resets on every command sent. The abandon monitor skips clients executing blocking commands (BLPOP, XREAD BLOCK, etc.). Set to 0 to disable abandon detection. Default: 5 minutes.

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

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]

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

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()

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]

IsolatedScope

A borrowed dedicated connection for operations requiring per-connection state.

Commands bypass the multiplexer and execute on a single TCP connection. Enables WATCH/MULTI/EXEC, CLIENT TRACKING, blocking commands, and pub/sub without interference from other callers.

Thread Safety: A single IsolatedScope is NOT thread-safe (serial execution). Multiple threads should each acquire their own scope via client.scoped_connection().

Use as a context manager for automatic release

with client.scoped_connection() as scope: scope.watch("key") ...

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
class IsolatedScope:
    """
    A borrowed dedicated connection for operations requiring per-connection state.

    Commands bypass the multiplexer and execute on a single TCP connection.
    Enables WATCH/MULTI/EXEC, CLIENT TRACKING, blocking commands, and pub/sub
    without interference from other callers.

    Thread Safety: A single IsolatedScope is NOT thread-safe (serial execution).
    Multiple threads should each acquire their own scope via client.scoped_connection().

    Use as a context manager for automatic release:
        with client.scoped_connection() as scope:
            scope.watch("key")
            ...
    """

    __slots__ = (
        "_scope_id",
        "_client_id",
        "_ffi",
        "_lib",
        "_released",
        "_response_parser",
        "_owner_thread",
    )

    def __init__(
        self, scope_id: int, client_id: int, ffi_instance: _GlideFFI, response_parser
    ):
        self._scope_id = scope_id
        self._client_id = client_id
        self._ffi = ffi_instance.ffi
        self._lib = ffi_instance.lib
        self._released = False
        self._response_parser = response_parser
        self._owner_thread = threading.current_thread().ident

    @property
    def scope_id(self) -> int:
        """The scope identifier handle."""
        if self._released:
            raise RuntimeError("Scope already released")
        return self._scope_id

    @property
    def is_released(self) -> bool:
        """Whether the scope has been returned to the pool."""
        return self._released

    # ═══════════════════════════════════════════════════════════════════════════
    # COMMANDS
    # ═══════════════════════════════════════════════════════════════════════════

    def watch(self, *keys: str) -> Optional[str]:
        """WATCH one or more keys for optimistic locking."""
        return self._cmd("WATCH", *keys)

    def unwatch(self) -> Optional[str]:
        """Discard all watched keys."""
        return self._cmd("UNWATCH")

    def multi(self) -> Optional[str]:
        """Begin a transaction block."""
        return self._cmd("MULTI")

    def exec(self) -> Optional[str]:
        """Execute the transaction (returns None if WATCH detected a conflict)."""
        return self._cmd("EXEC")

    def discard(self) -> Optional[str]:
        """Discard the transaction."""
        return self._cmd("DISCARD")

    def get(self, key: str) -> Optional[str]:
        """GET a key value."""
        return self._cmd("GET", key)

    def set(self, key: str, value: str) -> Optional[str]:
        """SET a key to a value."""
        return self._cmd("SET", key, value)

    def incr(self, key: str) -> Optional[str]:
        """Increment a key's integer value by 1."""
        return self._cmd("INCR", key)

    def ping(self, message: Optional[str] = None) -> Optional[str]:
        """PING the server."""
        if message:
            return self._cmd("PING", message)
        return self._cmd("PING")

    def select(self, db: int) -> Optional[str]:
        """SELECT a database by index."""
        return self._cmd("SELECT", str(db))

    def execute_command(self, command: str, *args: str) -> Optional[str]:
        """Execute an arbitrary command on this scope."""
        return self._cmd(command, *args)

    # ═══════════════════════════════════════════════════════════════════════════
    # INTERNAL
    # ═══════════════════════════════════════════════════════════════════════════

    def _cmd(self, command: str, *args: str) -> Optional[str]:
        """Serialize and execute a command on the scoped connection."""
        if self._released:
            raise RuntimeError("Scope already released")

        # Detect cross-thread usage — scopes are NOT thread-safe
        current = threading.current_thread().ident
        if current != self._owner_thread:
            raise RuntimeError(
                f"IsolatedScope used from thread {current} but was acquired on thread "
                f"{self._owner_thread}. Each thread must acquire its own scope."
            )

        # Serialize command in wire format (little-endian):
        # [4:cmd_len][cmd_bytes][4:num_args][4:arg1_len][arg1_bytes]...
        cmd_bytes = command.encode("utf-8")
        parts = [
            struct.pack("<I", len(cmd_bytes)),
            cmd_bytes,
            struct.pack("<I", len(args)),
        ]
        for arg in args:
            arg_bytes = arg.encode("utf-8")
            parts.append(struct.pack("<I", len(arg_bytes)))
            parts.append(arg_bytes)

        payload = b"".join(parts)

        # Call FFI
        buf = self._ffi.from_buffer(payload)
        result_ptr = self._lib.glide_scope_execute(
            self._scope_id,
            self._ffi.cast("const uint8_t*", buf),
            len(payload),
        )

        if result_ptr == self._ffi.NULL:
            raise RuntimeError(f"Scope execute failed: invalid scope {self._scope_id}")

        try:
            return self._parse_result(result_ptr)
        finally:
            self._lib.free_command_result(result_ptr)

    def _parse_result(self, result_ptr) -> Optional[str]:
        """Parse a CommandResult pointer into a Python value."""
        result = result_ptr

        # Check for error
        if result.command_error != self._ffi.NULL:
            err = result.command_error
            msg = self._ffi.string(err.command_error_message).decode("utf-8")
            raise RuntimeError(f"Scope command error: {msg}")

        # Parse response
        if result.response == self._ffi.NULL:
            return None

        return self._response_parser(result.response)

    # ═══════════════════════════════════════════════════════════════════════════
    # CONTEXT MANAGER
    # ═══════════════════════════════════════════════════════════════════════════

    def close(self):
        """Release the scope back to the pool."""
        if not self._released:
            self._released = True
            self._lib.glide_scope_release(self._scope_id, self._client_id)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
        return False

    def __del__(self):
        """Safety net — release on GC if not explicitly closed."""
        if not self._released:
            try:
                self.close()
            except Exception:
                pass

scope_id property

The scope identifier handle.

is_released property

Whether the scope has been returned to the pool.

watch(*keys)

WATCH one or more keys for optimistic locking.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
85
86
87
def watch(self, *keys: str) -> Optional[str]:
    """WATCH one or more keys for optimistic locking."""
    return self._cmd("WATCH", *keys)

unwatch()

Discard all watched keys.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
89
90
91
def unwatch(self) -> Optional[str]:
    """Discard all watched keys."""
    return self._cmd("UNWATCH")

multi()

Begin a transaction block.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
93
94
95
def multi(self) -> Optional[str]:
    """Begin a transaction block."""
    return self._cmd("MULTI")

exec()

Execute the transaction (returns None if WATCH detected a conflict).

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
97
98
99
def exec(self) -> Optional[str]:
    """Execute the transaction (returns None if WATCH detected a conflict)."""
    return self._cmd("EXEC")

discard()

Discard the transaction.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
101
102
103
def discard(self) -> Optional[str]:
    """Discard the transaction."""
    return self._cmd("DISCARD")

get(key)

GET a key value.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
105
106
107
def get(self, key: str) -> Optional[str]:
    """GET a key value."""
    return self._cmd("GET", key)

set(key, value)

SET a key to a value.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
109
110
111
def set(self, key: str, value: str) -> Optional[str]:
    """SET a key to a value."""
    return self._cmd("SET", key, value)

incr(key)

Increment a key's integer value by 1.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
113
114
115
def incr(self, key: str) -> Optional[str]:
    """Increment a key's integer value by 1."""
    return self._cmd("INCR", key)

ping(message=None)

PING the server.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
117
118
119
120
121
def ping(self, message: Optional[str] = None) -> Optional[str]:
    """PING the server."""
    if message:
        return self._cmd("PING", message)
    return self._cmd("PING")

select(db)

SELECT a database by index.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
123
124
125
def select(self, db: int) -> Optional[str]:
    """SELECT a database by index."""
    return self._cmd("SELECT", str(db))

execute_command(command, *args)

Execute an arbitrary command on this scope.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
127
128
129
def execute_command(self, command: str, *args: str) -> Optional[str]:
    """Execute an arbitrary command on this scope."""
    return self._cmd(command, *args)

close()

Release the scope back to the pool.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/isolated_scope.py
199
200
201
202
203
def close(self):
    """Release the scope back to the pool."""
    if not self._released:
        self._released = True
        self._lib.glide_scope_release(self._scope_id, self._client_id)

MonitorClient

A client that streams all commands processed by the server via the MONITOR command.

Must be used with a standalone (non-cluster) configuration. The configuration's lib_name and client_info_tag identify the dedicated monitor connection, using GlidePySync as the default library name.

Warning: MONITOR is a debugging tool with performance implications. Do not use in production environments.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/monitor_client.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
class MonitorClient:
    """
    A client that streams all commands processed by the server via the MONITOR command.

    Must be used with a standalone (non-cluster) configuration.
    The configuration's ``lib_name`` and ``client_info_tag`` identify the dedicated
    monitor connection, using ``GlidePySync`` as the default library name.

    Warning: MONITOR is a debugging tool with performance implications.
    Do not use in production environments.
    """

    def __init__(self) -> None:
        self._ffi = GlideFFI.ffi
        self._lib = GlideFFI.lib
        self._core_client = self._ffi.NULL
        self._callback_ref = None
        self._queue: List[MonitorMsg] = []
        self._lock = threading.Lock()
        self._condition = threading.Condition(self._lock)
        self._is_closed = False
        self._user_callback: Optional[Callable[[MonitorMsg], None]] = None

    @classmethod
    def create(
        cls,
        config: GlideClientConfiguration,
        callback: Optional[Callable[[MonitorMsg], None]] = None,
    ) -> "MonitorClient":
        """
        Create a new MonitorClient connected to the server.

        Args:
            config: Standalone client configuration (must be GlideClientConfiguration).
                    Its library-name override and client information tag are applied
                    to the dedicated monitor connection.
            callback: Optional callback invoked for each MonitorMsg. If None, messages
                      are queued and retrievable via get_monitor_message().

        Returns:
            A MonitorClient instance.
        """
        if not isinstance(config, GlideClientConfiguration):
            raise TypeError(
                "MonitorClient requires a GlideClientConfiguration (standalone only)"
            )
        iam_config = (
            config.credentials.iam_config if config.credentials is not None else None
        )
        if iam_config is not None:
            raise ConfigurationError(
                "MonitorClient does not support IAM authentication"
            )
        instance = cls()
        instance._user_callback = callback
        conn_req = _create_sync_connection_request(config)
        conn_req_bytes = conn_req.SerializeToString()

        @instance._ffi.callback("MonitorCallback")
        def _monitor_callback(
            client_ptr,
            timestamp,
            db,
            client_addr_ptr,
            client_addr_len,
            command_ptr,
            command_len,
            args_json_ptr,
            args_json_len,
        ):
            try:
                client_addr = bytes(
                    instance._ffi.buffer(client_addr_ptr, client_addr_len)
                ).decode("utf-8", errors="replace")
                command = bytes(instance._ffi.buffer(command_ptr, command_len)).decode(
                    "utf-8", errors="replace"
                )
                args_json_str = bytes(
                    instance._ffi.buffer(args_json_ptr, args_json_len)
                ).decode("utf-8", errors="replace")
                try:
                    args: List[str] = (
                        json.loads(args_json_str) if args_json_len > 0 else []
                    )
                except (json.JSONDecodeError, ValueError):
                    args = []
                msg = MonitorMsg(
                    timestamp=timestamp,
                    db=db,
                    client_addr=client_addr,
                    command=command,
                    args=args,
                )
                if instance._user_callback is not None:
                    instance._user_callback(msg)
                else:
                    with instance._condition:
                        instance._queue.append(msg)
                        instance._condition.notify()
            except Exception:
                pass  # Suppress callback errors to avoid crashing the Rust FFI layer

        instance._callback_ref = _monitor_callback
        client_response = instance._lib.create_monitor_client(
            conn_req_bytes, len(conn_req_bytes), _monitor_callback
        )
        if client_response == instance._ffi.NULL:
            raise RuntimeError("Failed to create monitor client: null response")
        if client_response.connection_error_message != instance._ffi.NULL:
            error = instance._ffi.string(
                client_response.connection_error_message
            ).decode()
            error_class = get_connection_error_class(
                client_response.connection_error_type, default=RuntimeError
            )
            instance._lib.free_connection_response(client_response)
            raise error_class(f"Failed to create monitor client: {error}")
        instance._core_client = client_response.conn_ptr
        instance._lib.free_connection_response(client_response)
        return instance

    def get_monitor_message(
        self, timeout: Optional[float] = None
    ) -> Optional[MonitorMsg]:
        """
        Block until a MonitorMsg is available, then return it.

        Args:
            timeout: Optional timeout in seconds. Returns None on timeout or if closed.
        """
        deadline = time.monotonic() + timeout if timeout is not None else None
        with self._condition:
            while not self._queue and not self._is_closed:
                remaining = None
                if deadline is not None:
                    remaining = deadline - time.monotonic()
                    if remaining <= 0:
                        break
                self._condition.wait(timeout=remaining)
            return self._queue.pop(0) if self._queue else None

    def try_get_monitor_message(self) -> Optional[MonitorMsg]:
        """Non-blocking retrieval. Returns None if no message is available."""
        with self._condition:
            return self._queue.pop(0) if self._queue else None

    def close(self) -> None:
        """Stop monitoring and release resources."""
        with self._condition:
            if self._is_closed:
                return
            self._is_closed = True
            self._condition.notify_all()
        if self._core_client != self._ffi.NULL:
            client = self._core_client
            self._core_client = self._ffi.NULL
            self._lib.close_monitor_client(client)
        self._callback_ref = None

    def stop(self) -> None:
        """Alias for close(). Stop monitoring and release resources."""
        self.close()

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

    def __exit__(self, *args) -> None:
        self.close()

create(config, callback=None) classmethod

Create a new MonitorClient connected to the server.

Parameters:

Name Type Description Default
config GlideClientConfiguration

Standalone client configuration (must be GlideClientConfiguration). Its library-name override and client information tag are applied to the dedicated monitor connection.

required
callback Optional[Callable[[MonitorMsg], None]]

Optional callback invoked for each MonitorMsg. If None, messages are queued and retrievable via get_monitor_message().

None

Returns:

Type Description
MonitorClient

A MonitorClient instance.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/monitor_client.py
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
@classmethod
def create(
    cls,
    config: GlideClientConfiguration,
    callback: Optional[Callable[[MonitorMsg], None]] = None,
) -> "MonitorClient":
    """
    Create a new MonitorClient connected to the server.

    Args:
        config: Standalone client configuration (must be GlideClientConfiguration).
                Its library-name override and client information tag are applied
                to the dedicated monitor connection.
        callback: Optional callback invoked for each MonitorMsg. If None, messages
                  are queued and retrievable via get_monitor_message().

    Returns:
        A MonitorClient instance.
    """
    if not isinstance(config, GlideClientConfiguration):
        raise TypeError(
            "MonitorClient requires a GlideClientConfiguration (standalone only)"
        )
    iam_config = (
        config.credentials.iam_config if config.credentials is not None else None
    )
    if iam_config is not None:
        raise ConfigurationError(
            "MonitorClient does not support IAM authentication"
        )
    instance = cls()
    instance._user_callback = callback
    conn_req = _create_sync_connection_request(config)
    conn_req_bytes = conn_req.SerializeToString()

    @instance._ffi.callback("MonitorCallback")
    def _monitor_callback(
        client_ptr,
        timestamp,
        db,
        client_addr_ptr,
        client_addr_len,
        command_ptr,
        command_len,
        args_json_ptr,
        args_json_len,
    ):
        try:
            client_addr = bytes(
                instance._ffi.buffer(client_addr_ptr, client_addr_len)
            ).decode("utf-8", errors="replace")
            command = bytes(instance._ffi.buffer(command_ptr, command_len)).decode(
                "utf-8", errors="replace"
            )
            args_json_str = bytes(
                instance._ffi.buffer(args_json_ptr, args_json_len)
            ).decode("utf-8", errors="replace")
            try:
                args: List[str] = (
                    json.loads(args_json_str) if args_json_len > 0 else []
                )
            except (json.JSONDecodeError, ValueError):
                args = []
            msg = MonitorMsg(
                timestamp=timestamp,
                db=db,
                client_addr=client_addr,
                command=command,
                args=args,
            )
            if instance._user_callback is not None:
                instance._user_callback(msg)
            else:
                with instance._condition:
                    instance._queue.append(msg)
                    instance._condition.notify()
        except Exception:
            pass  # Suppress callback errors to avoid crashing the Rust FFI layer

    instance._callback_ref = _monitor_callback
    client_response = instance._lib.create_monitor_client(
        conn_req_bytes, len(conn_req_bytes), _monitor_callback
    )
    if client_response == instance._ffi.NULL:
        raise RuntimeError("Failed to create monitor client: null response")
    if client_response.connection_error_message != instance._ffi.NULL:
        error = instance._ffi.string(
            client_response.connection_error_message
        ).decode()
        error_class = get_connection_error_class(
            client_response.connection_error_type, default=RuntimeError
        )
        instance._lib.free_connection_response(client_response)
        raise error_class(f"Failed to create monitor client: {error}")
    instance._core_client = client_response.conn_ptr
    instance._lib.free_connection_response(client_response)
    return instance

get_monitor_message(timeout=None)

Block until a MonitorMsg is available, then return it.

Parameters:

Name Type Description Default
timeout Optional[float]

Optional timeout in seconds. Returns None on timeout or if closed.

None
Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/monitor_client.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def get_monitor_message(
    self, timeout: Optional[float] = None
) -> Optional[MonitorMsg]:
    """
    Block until a MonitorMsg is available, then return it.

    Args:
        timeout: Optional timeout in seconds. Returns None on timeout or if closed.
    """
    deadline = time.monotonic() + timeout if timeout is not None else None
    with self._condition:
        while not self._queue and not self._is_closed:
            remaining = None
            if deadline is not None:
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    break
            self._condition.wait(timeout=remaining)
        return self._queue.pop(0) if self._queue else None

try_get_monitor_message()

Non-blocking retrieval. Returns None if no message is available.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/monitor_client.py
156
157
158
159
def try_get_monitor_message(self) -> Optional[MonitorMsg]:
    """Non-blocking retrieval. Returns None if no message is available."""
    with self._condition:
        return self._queue.pop(0) if self._queue else None

close()

Stop monitoring and release resources.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/monitor_client.py
161
162
163
164
165
166
167
168
169
170
171
172
def close(self) -> None:
    """Stop monitoring and release resources."""
    with self._condition:
        if self._is_closed:
            return
        self._is_closed = True
        self._condition.notify_all()
    if self._core_client != self._ffi.NULL:
        client = self._core_client
        self._core_client = self._ffi.NULL
        self._lib.close_monitor_client(client)
    self._callback_ref = None

stop()

Alias for close(). Stop monitoring and release resources.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/monitor_client.py
174
175
176
def stop(self) -> None:
    """Alias for close(). Stop monitoring and release resources."""
    self.close()

OpenTelemetry

Bases: OpenTelemetry

Sync client OpenTelemetry singleton (separate from async).

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/opentelemetry.py
11
12
13
14
15
class OpenTelemetry(_BaseOpenTelemetry):
    """Sync client OpenTelemetry singleton (separate from async)."""

    _instance = None
    _config = None

ClusterScanCursor

Bases: ClusterScanCursor

ClusterScanCursor using the sync package's FFI instance.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/sync_commands/cluster_scan_cursor.py
 7
 8
 9
10
11
class ClusterScanCursor(_ClusterScanCursorBase):
    """ClusterScanCursor using the sync package's FFI instance."""

    def __init__(self, new_cursor=None):
        super().__init__(new_cursor, _ffi=_SYNC_FFI.ffi, _lib=_SYNC_FFI.lib)

Script

Bases: Script

Script using the sync package's FFI instance.

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/sync_commands/script.py
 7
 8
 9
10
11
class Script(_ScriptBase):
    """Script using the sync package's FFI instance."""

    def __init__(self, code):
        super().__init__(code, _ffi=_SYNC_FFI.ffi, _lib=_SYNC_FFI.lib)

get_min_compressed_size()

Get the minimum compression size in bytes.

Returns the minimum size threshold for compression. Values smaller than this will not be compressed.

Returns:

Name Type Description
int int

The minimum compression size in bytes (currently 6 bytes: 5-byte header + 1 byte data)

Source code in doc-gen/valkey-glide/python/glide-sync/glide_sync/sync_commands/utils.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def get_min_compressed_size() -> int:
    """
    Get the minimum compression size in bytes.

    Returns the minimum size threshold for compression. Values smaller than this
    will not be compressed.

    Returns:
        int: The minimum compression size in bytes (currently 6 bytes: 5-byte header + 1 byte data)
    """
    _glide_ffi = _SYNC_FFI
    return _glide_ffi.lib.get_min_compressed_size()