matrix-compute-node 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,563 @@
1
+ """
2
+ Thread-Safe Pinned Tensor Session & Memory Lifecycle Management for matrix-compute-node.
3
+ Supports capacity bounding, memory footprint enforcement, hybrid TTL eviction,
4
+ and explicit buffer zeroization.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import logging
11
+ import threading
12
+ import time
13
+ from typing import Any, Dict, Iterator, Optional, Tuple, Union
14
+
15
+ import numpy as np
16
+
17
+ from src.engine.compute_core import ComputeEngine
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ # ==============================================================================
23
+ # EXCEPTIONS
24
+ # ==============================================================================
25
+
26
+ class SessionError(Exception):
27
+ """Base exception for stateful session management."""
28
+
29
+
30
+ class SessionNotFoundError(SessionError, KeyError):
31
+ """Raised when the specified lease_id is not found."""
32
+
33
+
34
+ class SessionExpiredError(SessionError, RuntimeError):
35
+ """Raised when an operation is attempted on an expired lease."""
36
+
37
+
38
+ class SessionCapacityError(SessionError, RuntimeError):
39
+ """Raised when maximum concurrent session limit is exceeded."""
40
+
41
+
42
+ class MemoryBoundError(SessionError, RuntimeError):
43
+ """Raised when memory allocation bounds are exceeded."""
44
+
45
+
46
+ class InvalidMatrixDimensionsError(SessionError, ValueError):
47
+ """Raised when matrix dimensions or byte payload sizes are invalid."""
48
+
49
+
50
+ # ==============================================================================
51
+ # TIMESTAMP HELPER
52
+ # ==============================================================================
53
+
54
+ class _IntTimestamp(int):
55
+ """
56
+ Subclass of int that allows being called as a function returning itself.
57
+ Handles callers using either session.expires_at_unix_ms or session.expires_at_unix_ms().
58
+ """
59
+
60
+ def __call__(self) -> int:
61
+ return int(self)
62
+
63
+
64
+ # ==============================================================================
65
+ # PINNED TENSOR SESSION
66
+ # ==============================================================================
67
+
68
+ class PinnedTensorSession:
69
+ """
70
+ Represents an allocated, pinned matrix session in worker memory/VRAM.
71
+ Manages lifetime, access tracking, and zeroization for a single lease.
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ lease_id: str,
77
+ matrix: Optional[np.ndarray],
78
+ rows: int,
79
+ cols: int,
80
+ dtype: str = "fp32",
81
+ ttl_seconds: float = 3600.0,
82
+ require_confidential_compute: bool = False,
83
+ client_pubkey: Optional[bytes] = None,
84
+ session_keys: Optional[Any] = None,
85
+ worker_ephemeral_pubkey: bytes = b"",
86
+ ) -> None:
87
+ self.lease_id = str(lease_id).strip()
88
+ self.matrix: Optional[np.ndarray] = matrix
89
+ self.rows = int(rows)
90
+ self.cols = int(cols)
91
+ self.dtype = str(dtype).lower().strip()
92
+ self.ttl_seconds = float(ttl_seconds)
93
+ self.created_at = time.time()
94
+ self.expires_at = self.created_at + self.ttl_seconds
95
+ self.last_accessed_at = self.created_at
96
+ self.require_confidential_compute = bool(require_confidential_compute)
97
+ self.client_pubkey = client_pubkey
98
+ self.session_keys = session_keys
99
+ self.worker_ephemeral_pubkey = worker_ephemeral_pubkey
100
+ self.step_count = 0
101
+ if matrix is not None:
102
+ self.memory_bytes = int(matrix.nbytes)
103
+ else:
104
+ elem_size = 4 if self.dtype in ("fp32", "bf16", "float32", "bfloat16") else 2
105
+ self.memory_bytes = int(self.rows * self.cols * elem_size)
106
+ self._zeroized = False
107
+ self._lock = threading.RLock()
108
+
109
+ @property
110
+ def is_zeroized(self) -> bool:
111
+ """Returns True if the session buffers have been zeroized."""
112
+ with self._lock:
113
+ return self._zeroized
114
+
115
+ @property
116
+ def np_dtype(self) -> np.dtype:
117
+ """Returns corresponding NumPy datatype."""
118
+ if self.dtype in ("fp16", "float16"):
119
+ return np.float16
120
+ return np.float32
121
+
122
+ @property
123
+ def is_valid(self) -> bool:
124
+ """Returns True if the session is not zeroized and within TTL."""
125
+ with self._lock:
126
+ return not self._zeroized and not self.is_expired()
127
+
128
+ @property
129
+ def expires_at_unix_ms(self) -> _IntTimestamp:
130
+ """Returns expiration time in milliseconds for gRPC response messages."""
131
+ with self._lock:
132
+ return _IntTimestamp(int(self.expires_at * 1000))
133
+
134
+ def is_expired(self, current_time: Optional[float] = None) -> bool:
135
+ """Checks if session has reached its TTL expiration timestamp."""
136
+ with self._lock:
137
+ if self._zeroized:
138
+ return True
139
+ now = current_time if current_time is not None else time.time()
140
+ return now >= self.expires_at
141
+
142
+ def touch(self, current_time: Optional[float] = None, extend_ttl: bool = False) -> None:
143
+ """Updates last_accessed_at timestamp and optionally refreshes TTL."""
144
+ with self._lock:
145
+ if self._zeroized:
146
+ raise SessionExpiredError(f"Cannot touch zeroized session '{self.lease_id}'")
147
+ now = current_time if current_time is not None else time.time()
148
+ self.last_accessed_at = now
149
+ if extend_ttl:
150
+ self.expires_at = now + self.ttl_seconds
151
+
152
+ def record_step(self) -> int:
153
+ """Records execution of an iterative step, updating step count and access timestamp."""
154
+ with self._lock:
155
+ if self._zeroized or self.is_expired():
156
+ raise SessionExpiredError(f"Session '{self.lease_id}' is expired or zeroized")
157
+ self.step_count += 1
158
+ self.last_accessed_at = time.time()
159
+ return self.step_count
160
+
161
+ def zeroize(self) -> int:
162
+ """
163
+ Securely clears pinned memory buffers and cryptographic session keys.
164
+ Overwrites matrix buffer with zeros before releasing reference.
165
+ Returns the number of memory bytes freed.
166
+ """
167
+ with self._lock:
168
+ if self._zeroized:
169
+ return 0
170
+ freed = self.memory_bytes
171
+ if self.matrix is not None:
172
+ try:
173
+ if isinstance(self.matrix, np.ndarray):
174
+ if not self.matrix.flags.writeable:
175
+ self.matrix.setflags(write=True)
176
+ self.matrix.fill(0)
177
+ except Exception as exc:
178
+ logger.warning("Error zeroizing matrix for lease '%s': %s", self.lease_id, exc)
179
+ self.matrix = None
180
+
181
+ if self.session_keys is not None:
182
+ try:
183
+ if hasattr(self.session_keys, "zeroize"):
184
+ self.session_keys.zeroize()
185
+ except Exception as exc:
186
+ logger.warning("Error zeroizing session keys for lease '%s': %s", self.lease_id, exc)
187
+ self.session_keys = None
188
+
189
+ self.client_pubkey = None
190
+ self._zeroized = True
191
+ return freed
192
+
193
+ def __iter__(self) -> Iterator[Any]:
194
+ """Allows unpacking (session, worker_ephemeral_pubkey) for tuple-based consumers."""
195
+ yield self
196
+ yield self.worker_ephemeral_pubkey
197
+
198
+ def __getitem__(self, item: int) -> Any:
199
+ if item == 0:
200
+ return self
201
+ elif item == 1:
202
+ return self.worker_ephemeral_pubkey
203
+ raise IndexError(f"Index {item} out of bounds for PinnedTensorSession tuple unpacking")
204
+
205
+
206
+ # ==============================================================================
207
+ # SESSION MANAGER
208
+ # ==============================================================================
209
+
210
+ class SessionManager:
211
+ """
212
+ Thread-safe in-memory session manager for pinned matrix tensors.
213
+ Enforces maximum session count, memory bounds, and hybrid TTL eviction.
214
+ """
215
+
216
+ def __init__(
217
+ self,
218
+ max_sessions: int = 100,
219
+ max_memory_bytes: int = 4 * 1024 * 1024 * 1024, # 4 GB
220
+ max_matrix_bytes: int = 1024 * 1024 * 1024, # 1 GB
221
+ default_ttl_seconds: float = 3600.0, # 1 hour
222
+ max_ttl_seconds: float = 86400.0, # 24 hours
223
+ reaper_interval_seconds: float = 10.0, # 10 seconds
224
+ compute_engine: Optional[ComputeEngine] = None,
225
+ auto_start_reaper: bool = True,
226
+ engine: Optional[ComputeEngine] = None,
227
+ max_active_sessions: Optional[int] = None,
228
+ max_total_memory_bytes: Optional[int] = None,
229
+ ) -> None:
230
+ self.max_sessions = max_active_sessions if max_active_sessions is not None else max_sessions
231
+ self.max_memory_bytes = max_total_memory_bytes if max_total_memory_bytes is not None else max_memory_bytes
232
+ self.max_matrix_bytes = max_matrix_bytes
233
+ self.default_ttl_seconds = default_ttl_seconds
234
+ self.max_ttl_seconds = max_ttl_seconds
235
+ self.reaper_interval_seconds = reaper_interval_seconds
236
+ self.compute_engine = engine or compute_engine or ComputeEngine()
237
+
238
+ self._sessions: Dict[str, PinnedTensorSession] = {}
239
+ self._total_memory_bytes: int = 0
240
+ self._lock = threading.RLock()
241
+ self._stop_event = threading.Event()
242
+ self._reaper_thread: Optional[threading.Thread] = None
243
+
244
+ if auto_start_reaper:
245
+ self._start_reaper()
246
+
247
+ def _start_reaper(self) -> None:
248
+ """Starts background daemon reaper thread for proactive TTL eviction."""
249
+ if self._reaper_thread is None or not self._reaper_thread.is_alive():
250
+ self._stop_event.clear()
251
+ self._reaper_thread = threading.Thread(
252
+ target=self._reaper_loop,
253
+ daemon=True,
254
+ name="MatrixSessionReaper",
255
+ )
256
+ self._reaper_thread.start()
257
+
258
+ def _reaper_loop(self) -> None:
259
+ """Daemon thread loop waking every reaper_interval_seconds to purge expired leases."""
260
+ while not self._stop_event.is_set():
261
+ if self._stop_event.wait(timeout=self.reaper_interval_seconds):
262
+ break
263
+ try:
264
+ freed = self.evict_expired()
265
+ if freed > 0:
266
+ logger.debug("SessionReaper reclaimed %d bytes from expired sessions", freed)
267
+ except Exception as exc:
268
+ logger.warning("Unexpected error in SessionReaper loop: %s", exc)
269
+
270
+ def lease_matrix(
271
+ self,
272
+ lease_id: str,
273
+ *args: Any,
274
+ matrix_bytes: Optional[bytes] = None,
275
+ matrix: Optional[np.ndarray] = None,
276
+ rows: Optional[int] = None,
277
+ cols: Optional[int] = None,
278
+ dtype: Optional[str] = None,
279
+ ttl_seconds: Optional[Union[int, float]] = None,
280
+ require_confidential_compute: bool = False,
281
+ client_ephemeral_pubkey: Optional[bytes] = None,
282
+ worker_ephemeral_priv: Optional[Any] = None,
283
+ worker_nonce: bytes = b"",
284
+ session_keys: Optional[Any] = None,
285
+ **kwargs: Any,
286
+ ) -> PinnedTensorSession:
287
+ """
288
+ Allocates and pins matrix A for a new stateful session.
289
+ Enforces capacity limits, memory bounds, and parses raw matrix bytes.
290
+
291
+ Flexible parameter handling supports:
292
+ - lease_matrix(lease_id, matrix_bytes, rows, cols, dtype, ttl_seconds)
293
+ - lease_matrix(lease_id, rows, cols, dtype, matrix_bytes, ttl_seconds)
294
+ - lease_matrix(lease_id, matrix, rows, cols, dtype, ttl_seconds)
295
+ """
296
+ # Step 1: Lazy TTL eviction before evaluating capacity
297
+ self.evict_expired()
298
+
299
+ clean_id = str(lease_id).strip()
300
+ if not clean_id:
301
+ raise ValueError("lease_id must not be empty")
302
+
303
+ # Parse positional args if provided
304
+ mat_or_bytes = matrix_bytes if matrix_bytes is not None else matrix
305
+ if len(args) > 0:
306
+ first_arg = args[0]
307
+ if isinstance(first_arg, (bytes, bytearray, np.ndarray)):
308
+ mat_or_bytes = first_arg
309
+ if len(args) > 1 and rows is None:
310
+ rows = args[1]
311
+ if len(args) > 2 and cols is None:
312
+ cols = args[2]
313
+ if len(args) > 3 and dtype is None:
314
+ dtype = args[3]
315
+ if len(args) > 4 and ttl_seconds is None:
316
+ ttl_seconds = args[4]
317
+ elif isinstance(first_arg, (int, float)):
318
+ if rows is None:
319
+ rows = int(first_arg)
320
+ if len(args) > 1 and cols is None:
321
+ cols = int(args[1])
322
+ if len(args) > 2 and dtype is None:
323
+ dtype = str(args[2])
324
+ if len(args) > 3 and mat_or_bytes is None:
325
+ mat_or_bytes = args[3]
326
+ if len(args) > 4 and ttl_seconds is None:
327
+ ttl_seconds = args[4]
328
+
329
+ if rows is None or cols is None or rows <= 0 or cols <= 0:
330
+ raise InvalidMatrixDimensionsError(
331
+ f"Matrix dimensions must be positive integers, got {rows}x{cols}"
332
+ )
333
+
334
+ norm_dtype = (dtype or "fp32").lower().strip()
335
+ if norm_dtype in ("float32", "fp32"):
336
+ norm_dtype = "fp32"
337
+ elem_size = 4
338
+ np_dtype = np.float32
339
+ elif norm_dtype in ("float16", "fp16"):
340
+ norm_dtype = "fp16"
341
+ elem_size = 2
342
+ np_dtype = np.float16
343
+ elif norm_dtype in ("bfloat16", "bf16"):
344
+ norm_dtype = "bf16"
345
+ np_dtype = np.float32
346
+ # Check length of bytes if provided
347
+ if isinstance(mat_or_bytes, (bytes, bytearray)):
348
+ elem_size = 4 if len(mat_or_bytes) == rows * cols * 4 else 2
349
+ else:
350
+ elem_size = 4
351
+ else:
352
+ raise ValueError(f"Unsupported dtype '{dtype}'. Supported: 'fp32', 'fp16', 'bf16'")
353
+
354
+ # Step 2: Handle confidential key exchange if requested and not pre-derived
355
+ worker_pubkey_bytes = b""
356
+ if require_confidential_compute and session_keys is None:
357
+ if client_ephemeral_pubkey is None or len(client_ephemeral_pubkey) != 32:
358
+ raise ValueError("client_ephemeral_pubkey must be exactly 32 bytes for confidential compute")
359
+
360
+ from cryptography.hazmat.primitives.asymmetric import x25519
361
+ from cryptography.hazmat.primitives import serialization
362
+ from src.engine.enclave_compute import derive_session_keys
363
+
364
+ priv_key = worker_ephemeral_priv or x25519.X25519PrivateKey.generate()
365
+ pub_key = priv_key.public_key()
366
+ worker_pubkey_bytes = pub_key.public_bytes(
367
+ encoding=serialization.Encoding.Raw,
368
+ format=serialization.PublicFormat.Raw,
369
+ )
370
+
371
+ salt = hashlib.sha256(f"iterative:{clean_id}".encode("utf-8")).digest()
372
+ session_keys = derive_session_keys(
373
+ worker_priv=priv_key,
374
+ client_pub_bytes=client_ephemeral_pubkey,
375
+ client_nonce=salt,
376
+ worker_nonce=worker_nonce,
377
+ )
378
+
379
+ # Step 3: Reconstruct and pin matrix in memory
380
+ if isinstance(mat_or_bytes, np.ndarray):
381
+ matrix_arr = mat_or_bytes
382
+ if matrix_arr.shape != (rows, cols):
383
+ raise InvalidMatrixDimensionsError(
384
+ f"Matrix shape mismatch: got {matrix_arr.shape}, expected ({rows}, {cols})"
385
+ )
386
+ if not matrix_arr.flags.writeable:
387
+ matrix_arr = matrix_arr.copy()
388
+ if norm_dtype == "bf16":
389
+ matrix_arr = ComputeEngine.truncate_to_bf16(matrix_arr)
390
+ elif isinstance(mat_or_bytes, (bytes, bytearray)):
391
+ expected_bytes = rows * cols * elem_size
392
+ if len(mat_or_bytes) != expected_bytes:
393
+ # Also check alternative 4-byte or 2-byte representation for bf16
394
+ if norm_dtype == "bf16" and len(mat_or_bytes) in (rows * cols * 2, rows * cols * 4):
395
+ elem_size = 4 if len(mat_or_bytes) == rows * cols * 4 else 2
396
+ else:
397
+ raise InvalidMatrixDimensionsError(
398
+ f"Matrix byte size mismatch: expected {expected_bytes} bytes for "
399
+ f"{rows}x{cols} ({norm_dtype}), got {len(mat_or_bytes)} bytes"
400
+ )
401
+
402
+ writable_bytes = bytearray(mat_or_bytes)
403
+ if norm_dtype == "bf16" and elem_size == 2:
404
+ u16 = np.frombuffer(writable_bytes, dtype=np.uint16).reshape((rows, cols))
405
+ u32 = u16.astype(np.uint32) << 16
406
+ raw_matrix = u32.view(np.float32)
407
+ matrix_arr = ComputeEngine.truncate_to_bf16(raw_matrix)
408
+ elif norm_dtype == "bf16":
409
+ raw_matrix = np.frombuffer(writable_bytes, dtype=np.float32).reshape((rows, cols))
410
+ matrix_arr = ComputeEngine.truncate_to_bf16(raw_matrix)
411
+ else:
412
+ matrix_arr = np.frombuffer(writable_bytes, dtype=np_dtype).reshape((rows, cols))
413
+ else:
414
+ raise InvalidMatrixDimensionsError("Must provide either matrix_bytes or matrix array")
415
+
416
+ pinned_matrix = matrix_arr
417
+ alloc_bytes = int(pinned_matrix.nbytes)
418
+
419
+ # Step 4: Validate capacity and bounds under lock
420
+ with self._lock:
421
+ if alloc_bytes > self.max_matrix_bytes:
422
+ raise MemoryBoundError(
423
+ f"Memory limit exceeded: matrix size ({alloc_bytes} bytes) exceeds maximum "
424
+ f"single matrix limit ({self.max_matrix_bytes} bytes)"
425
+ )
426
+
427
+ if clean_id in self._sessions:
428
+ existing = self._sessions[clean_id]
429
+ if not existing.is_expired():
430
+ raise ValueError(f"Lease '{clean_id}' already exists")
431
+ # Clean up existing expired session
432
+ self._total_memory_bytes -= existing.zeroize()
433
+ del self._sessions[clean_id]
434
+
435
+ if len(self._sessions) >= self.max_sessions:
436
+ raise SessionCapacityError(
437
+ f"Maximum sessions capacity exceeded: limit {self.max_sessions}"
438
+ )
439
+
440
+ if self._total_memory_bytes + alloc_bytes > self.max_memory_bytes:
441
+ raise MemoryBoundError(
442
+ f"Memory limit exceeded: insufficient memory (requested {alloc_bytes} bytes, "
443
+ f"currently used {self._total_memory_bytes} bytes, limit {self.max_memory_bytes} bytes)"
444
+ )
445
+
446
+ # Resolve TTL
447
+ eff_ttl = float(ttl_seconds if ttl_seconds and ttl_seconds > 0 else self.default_ttl_seconds)
448
+ eff_ttl = min(eff_ttl, self.max_ttl_seconds)
449
+
450
+ session = PinnedTensorSession(
451
+ lease_id=clean_id,
452
+ matrix=pinned_matrix,
453
+ rows=rows,
454
+ cols=cols,
455
+ dtype=norm_dtype,
456
+ ttl_seconds=eff_ttl,
457
+ require_confidential_compute=require_confidential_compute,
458
+ client_pubkey=client_ephemeral_pubkey,
459
+ session_keys=session_keys,
460
+ worker_ephemeral_pubkey=worker_pubkey_bytes,
461
+ )
462
+
463
+ self._sessions[clean_id] = session
464
+ self._total_memory_bytes += alloc_bytes
465
+
466
+ logger.info(
467
+ "Leased matrix for session '%s': %dx%d, %s, %d bytes, TTL=%.1fs (active sessions: %d)",
468
+ clean_id, rows, cols, norm_dtype, alloc_bytes, eff_ttl, len(self._sessions),
469
+ )
470
+ return session
471
+
472
+ def get_session(self, lease_id: str, allow_expired: bool = False) -> Optional[PinnedTensorSession]:
473
+ """
474
+ Retrieves active session for lease_id.
475
+ Performs lazy eviction if session has expired, returning None unless allow_expired=True.
476
+ """
477
+ clean_id = str(lease_id).strip()
478
+ with self._lock:
479
+ session = self._sessions.get(clean_id)
480
+ if session is None:
481
+ return None
482
+
483
+ if session.is_expired():
484
+ if allow_expired:
485
+ return session
486
+ logger.info("Lazy eviction: Session '%s' expired, releasing resources", clean_id)
487
+ self._sessions.pop(clean_id, None)
488
+ freed = session.zeroize()
489
+ self._total_memory_bytes = max(0, self._total_memory_bytes - freed)
490
+ return None
491
+
492
+ session.touch()
493
+ return session
494
+
495
+ def release_lease(self, lease_id: str) -> int:
496
+ """
497
+ Explicitly releases and zeroizes an active lease.
498
+ Returns the number of memory bytes freed.
499
+ """
500
+ clean_id = str(lease_id).strip()
501
+ with self._lock:
502
+ session = self._sessions.pop(clean_id, None)
503
+ if session is None:
504
+ return 0
505
+ freed = session.zeroize()
506
+ self._total_memory_bytes = max(0, self._total_memory_bytes - freed)
507
+
508
+ logger.info("Explicit release of lease '%s': reclaimed %d bytes", clean_id, freed)
509
+ return freed
510
+
511
+ def evict_expired(self, current_time: Optional[float] = None) -> int:
512
+ """
513
+ Scans all sessions, zeroizes and evicts those that have expired.
514
+ Returns total bytes freed.
515
+ """
516
+ now = current_time if current_time is not None else time.time()
517
+ total_freed = 0
518
+ with self._lock:
519
+ expired_ids = [lid for lid, s in self._sessions.items() if s.is_expired(now)]
520
+ for lid in expired_ids:
521
+ session = self._sessions.pop(lid, None)
522
+ if session is not None:
523
+ freed = session.zeroize()
524
+ total_freed += freed
525
+ self._total_memory_bytes = max(0, self._total_memory_bytes - freed)
526
+ logger.info("Evicted expired session '%s' (reclaimed %d bytes)", lid, freed)
527
+ return total_freed
528
+
529
+ @property
530
+ def active_session_count(self) -> int:
531
+ """Returns current count of active sessions."""
532
+ with self._lock:
533
+ return len(self._sessions)
534
+
535
+ @property
536
+ def total_memory_bytes(self) -> int:
537
+ """Returns total bytes currently allocated across all active pinned sessions."""
538
+ with self._lock:
539
+ return self._total_memory_bytes
540
+
541
+ @property
542
+ def is_shutdown(self) -> bool:
543
+ """Returns True if the session manager has been shut down."""
544
+ return self._stop_event.is_set()
545
+
546
+ def shutdown(self) -> None:
547
+ """Stops background reaper thread and zeroizes all active sessions."""
548
+ self._stop_event.set()
549
+ if self._reaper_thread is not None and self._reaper_thread.is_alive():
550
+ self._reaper_thread.join(timeout=2.0)
551
+ self._reaper_thread = None
552
+
553
+ with self._lock:
554
+ for session in list(self._sessions.values()):
555
+ session.zeroize()
556
+ self._sessions.clear()
557
+ self._total_memory_bytes = 0
558
+
559
+ def __enter__(self) -> "SessionManager":
560
+ return self
561
+
562
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
563
+ self.shutdown()