Storage
labchain.base.base_storage
¶
__all__ = ['BaseStorage', 'BaseSingleton']
module-attribute
¶
BaseLockingStorage
¶
Bases: BaseStorage
Base class for storage backends with distributed locking support.
This abstract class defines the interface for storage backends that support both file operations and distributed locking mechanisms. The locking system ensures safe concurrent access to cached artifacts across multiple processes or machines.
Storage backends must implement atomic lock acquisition to prevent race conditions when multiple processes try to generate the same cached artifact simultaneously.
Examples:
Basic storage implementation pattern:
class MyStorage(BaseStorage):
def exists(self, path: str) -> bool:
# Check if file exists in your storage
return my_storage_client.file_exists(path)
def try_acquire_lock(self, lock_name: str, ttl: int = 3600) -> bool:
# Atomic lock acquisition
return my_storage_client.create_if_not_exists(
f"locks/{lock_name}.lock"
)
Note
All lock operations must be atomic to guarantee correctness in distributed environments. Non-atomic implementations will lead to race conditions.
Source code in labchain/base/base_storage.py
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 | |
release_lock(lock_name)
abstractmethod
¶
Release a previously acquired lock.
Makes the lock available for other processes. Safe to call even if the lock doesn't exist or was already released.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lock_name
|
str
|
Identifier of the lock to release. |
required |
Examples:
storage.acquire_lock("model_abc123")
try:
train_model()
finally:
storage.release_lock("model_abc123")
Source code in labchain/base/base_storage.py
try_acquire_lock(lock_name, ttl=3600, heartbeat_interval=None)
abstractmethod
¶
Try to acquire a distributed lock atomically.
This operation must be atomic to prevent race conditions. Only one process across all machines should be able to acquire a lock with the same name at any given time.
The lock includes a TTL (time-to-live) for automatic recovery from crashed processes. If a process crashes while holding a lock, other processes can steal it after the TTL expires.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lock_name
|
str
|
Unique identifier for the lock. Should be descriptive, e.g., "model_abc123" or "data_xyz789". |
required |
ttl
|
int
|
Time-to-live in seconds. After this time, the lock is considered stale and can be stolen by other processes. Default is 3600 (1 hour). |
3600
|
heartbeat_interval
|
int | None
|
Optional interval in seconds for heartbeat updates. If provided, enables crash detection. Should be ttl/10 or smaller. Default None (no heartbeat). |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the lock was successfully acquired, False if another |
bool
|
process holds the lock. |
Examples:
# Try to acquire lock for training a model
if storage.try_acquire_lock("model_abc123", ttl=7200):
try:
# Train model - you have exclusive access
train_model()
save_model()
finally:
storage.release_lock("model_abc123")
else:
# Another process is training, wait for it
storage.wait_for_unlock("model_abc123")
load_cached_model()
Note
Always release locks in a try-finally block to prevent deadlocks.
Source code in labchain/base/base_storage.py
wait_for_unlock(lock_name, timeout=7200, initial_poll_interval=0.5, max_poll_interval=10.0, backoff_factor=1.5)
¶
Wait for a lock to be released with exponential backoff.
Uses exponential backoff to reduce polling frequency over time,
minimizing resource usage while still being responsive.
Args:
lock_name: Identifier of the lock to wait for.
timeout: Maximum time to wait in seconds. Default 7200 (2 hours).
initial_poll_interval: Initial time between checks in seconds. Default 0.5.
max_poll_interval: Maximum time between checks in seconds. Default 10.0.
backoff_factor: Multiplier for poll interval after each check. Default 1.5.
Returns:
True if the lock was released within the timeout, False if timeout
was reached.
Examples:
python
# Quick response initially, then less frequent checks
if storage.wait_for_unlock("model_abc123", timeout=3600):
load_model()
else:
raise TimeoutError("Training took too long")
Note:
Polling pattern with default settings (backoff=1.5):
| Check | Interval | Cumulative Time |
|-------|----------|----------------|
| 1 | 0.5s | 0.5s |
| 2 | 0.75s | 1.25s |
| 3 | 1.13s | 2.38s |
| 4 | 1.69s | 4.07s |
| 5 | 2.53s | 6.60s |
| ... | ... | ... |
| 15 | 10.0s | ~60s |
| ... | 10.0s | ... |
For a 30-minute wait:
- Fixed 0.5s polling: 3,600 checks
- Exponential backoff: ~150 checks (24x reduction!)
Source code in labchain/base/base_storage.py
BaseSingleton
¶
A base class for implementing the Singleton pattern.
This class ensures that only one instance of each derived class is created.
Key Features
- Implements the Singleton design pattern
- Allows derived classes to have only one instance
Usage
To create a Singleton class, inherit from BaseSingleton:
Attributes:
| Name | Type | Description |
|---|---|---|
_instances |
Dict[Type[BaseSingleton], Any]
|
A class-level dictionary to store instances. |
Methods:
| Name | Description |
|---|---|
__new__ |
Type[BaseSingleton], args: Any, *kwargs: Any) -> BaseStorage: Creates a new instance or returns the existing one. |
Note
This class should be used as a base class for any class that needs to implement the Singleton pattern.
Source code in labchain/base/base_storage.py
__new__(*args, **kwargs)
¶
Create a new instance of the class if it doesn't exist, otherwise return the existing instance.
This method implements the core logic of the Singleton pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Variable length argument list. |
()
|
**kwargs
|
Any
|
Arbitrary keyword arguments. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseStorage |
BaseStorage
|
The single instance of the class. |
Note
This method is called before init when creating a new instance of the class.
Source code in labchain/base/base_storage.py
BaseStorage
¶
Bases: BasePlugin, BaseSingleton
An abstract base class for storage operations.
This class defines the interface for storage-related operations and inherits from BasePlugin for plugin functionality and BaseSingleton for single instance behavior.
Key Features
- Abstract methods for common storage operations
- Singleton behavior ensures only one instance per storage type
- Inherits plugin functionality from BasePlugin
Usage
To create a new storage type, inherit from BaseStorage and implement all abstract methods:
class MyCustomStorage(BaseStorage):
def __init__(self, root_path: str):
self.root_path = root_path
def get_root_path(self) -> str:
return self.root_path
def upload_file(self, file, file_name: str, context: str, direct_stream: bool = False) -> str | None:
# Implement file upload logic
...
# Implement other abstract methods
...
# Usage
storage = MyCustomStorage("/path/to/storage")
storage.upload_file(file_object, "example.txt", "documents")
Methods:
| Name | Description |
|---|---|
get_root_path |
Abstract method to get the root path of the storage. |
upload_file |
object, file_name: str, context: str, direct_stream: bool = False) -> str | None: Abstract method to upload a file to the storage. |
download_file |
str, context: str) -> Any: Abstract method to download a file from the storage. |
list_stored_files |
str) -> List[Any]: Abstract method to list all files stored in a specific context. |
get_file_by_hashcode |
str, context: str) -> Any: Abstract method to retrieve a file by its hashcode. |
check_if_exists |
str, context: str) -> bool: Abstract method to check if a file exists in the storage. |
delete_file |
str, context: str): Abstract method to delete a file from the storage. |
Note
This is an abstract base class. Concrete implementations should override all abstract methods to provide specific storage functionality.
Source code in labchain/base/base_storage.py
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 | |
check_if_exists(hashcode, context)
abstractmethod
¶
Check if a file exists in the storage.
This method should be implemented to verify the existence of a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hashcode
|
str
|
The identifier of the file. |
required |
context
|
str
|
The context or directory of the file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the file exists, False otherwise. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the subclass does not implement this method. |
Example
Source code in labchain/base/base_storage.py
delete_file(hashcode, context)
abstractmethod
¶
Delete a file from the storage.
This method should be implemented to remove a file from the storage system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hashcode
|
str
|
The identifier of the file to delete. |
required |
context
|
str
|
The context or directory of the file. |
required |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the subclass does not implement this method. |
Example
Source code in labchain/base/base_storage.py
download_file(hashcode, context)
abstractmethod
¶
Download a file from the storage.
This method should be implemented to retrieve files from the storage system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hashcode
|
str
|
The identifier of the file to download. |
required |
context
|
str
|
The context or directory of the file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The downloaded file object. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the subclass does not implement this method. |
Example
Source code in labchain/base/base_storage.py
get_file_by_hashcode(hashcode, context)
abstractmethod
¶
Retrieve a file by its hashcode.
This method should be implemented to fetch a specific file using its identifier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hashcode
|
str
|
The identifier of the file. |
required |
context
|
str
|
The context or directory of the file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The file object or file information. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the subclass does not implement this method. |
Example
Source code in labchain/base/base_storage.py
get_root_path()
abstractmethod
¶
Get the root path of the storage.
This method should be implemented to return the base directory or path where the storage system keeps its files.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The root path of the storage. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the subclass does not implement this method. |
Source code in labchain/base/base_storage.py
list_stored_files(context)
abstractmethod
¶
List all files stored in a specific context.
This method should be implemented to return a list of files in a given context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
str
|
The context or directory to list files from. |
required |
Returns:
| Type | Description |
|---|---|
List[Any]
|
List[Any]: A list of file objects or file information. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the subclass does not implement this method. |
Example
Source code in labchain/base/base_storage.py
upload_file(file, file_name, context, direct_stream=False)
abstractmethod
¶
Upload a file to the storage.
This method should be implemented to handle file uploads to the storage system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
object
|
The file object to upload. |
required |
file_name
|
str
|
The name of the file. |
required |
context
|
str
|
The context or directory for the file. |
required |
direct_stream
|
bool
|
Whether to use direct streaming. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The identifier of the uploaded file, or None if upload failed. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the subclass does not implement this method. |