aws-durable-execution-sdk-python 1.0.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.
Files changed (36) hide show
  1. aws_durable_execution_sdk_python/.gitignore +0 -0
  2. aws_durable_execution_sdk_python/__about__.py +4 -0
  3. aws_durable_execution_sdk_python/__init__.py +34 -0
  4. aws_durable_execution_sdk_python/botocore/data/lambdainternal/2015-03-31/service-2.json +7864 -0
  5. aws_durable_execution_sdk_python/concurrency/__init__.py +0 -0
  6. aws_durable_execution_sdk_python/concurrency/executor.py +436 -0
  7. aws_durable_execution_sdk_python/concurrency/models.py +469 -0
  8. aws_durable_execution_sdk_python/config.py +499 -0
  9. aws_durable_execution_sdk_python/context.py +551 -0
  10. aws_durable_execution_sdk_python/exceptions.py +374 -0
  11. aws_durable_execution_sdk_python/execution.py +428 -0
  12. aws_durable_execution_sdk_python/identifier.py +14 -0
  13. aws_durable_execution_sdk_python/lambda_service.py +1034 -0
  14. aws_durable_execution_sdk_python/logger.py +131 -0
  15. aws_durable_execution_sdk_python/operation/__init__.py +1 -0
  16. aws_durable_execution_sdk_python/operation/callback.py +123 -0
  17. aws_durable_execution_sdk_python/operation/child.py +162 -0
  18. aws_durable_execution_sdk_python/operation/invoke.py +119 -0
  19. aws_durable_execution_sdk_python/operation/map.py +137 -0
  20. aws_durable_execution_sdk_python/operation/parallel.py +122 -0
  21. aws_durable_execution_sdk_python/operation/step.py +269 -0
  22. aws_durable_execution_sdk_python/operation/wait.py +53 -0
  23. aws_durable_execution_sdk_python/operation/wait_for_condition.py +235 -0
  24. aws_durable_execution_sdk_python/py.typed +1 -0
  25. aws_durable_execution_sdk_python/retries.py +174 -0
  26. aws_durable_execution_sdk_python/serdes.py +502 -0
  27. aws_durable_execution_sdk_python/state.py +790 -0
  28. aws_durable_execution_sdk_python/suspend.py +84 -0
  29. aws_durable_execution_sdk_python/threading.py +222 -0
  30. aws_durable_execution_sdk_python/types.py +180 -0
  31. aws_durable_execution_sdk_python/waits.py +130 -0
  32. aws_durable_execution_sdk_python-1.0.0.dist-info/METADATA +679 -0
  33. aws_durable_execution_sdk_python-1.0.0.dist-info/RECORD +36 -0
  34. aws_durable_execution_sdk_python-1.0.0.dist-info/WHEEL +4 -0
  35. aws_durable_execution_sdk_python-1.0.0.dist-info/licenses/LICENSE +175 -0
  36. aws_durable_execution_sdk_python-1.0.0.dist-info/licenses/NOTICE +1 -0
@@ -0,0 +1,790 @@
1
+ """Model for execution state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import queue
8
+ import threading
9
+ import time
10
+ from dataclasses import dataclass
11
+ from enum import Enum
12
+ from threading import Lock
13
+ from typing import TYPE_CHECKING
14
+
15
+ from aws_durable_execution_sdk_python.exceptions import (
16
+ BackgroundThreadError,
17
+ CallableRuntimeError,
18
+ DurableExecutionsError,
19
+ )
20
+ from aws_durable_execution_sdk_python.lambda_service import (
21
+ CheckpointOutput,
22
+ DurableServiceClient,
23
+ ErrorObject,
24
+ Operation,
25
+ OperationAction,
26
+ OperationStatus,
27
+ OperationType,
28
+ OperationUpdate,
29
+ StateOutput,
30
+ )
31
+ from aws_durable_execution_sdk_python.threading import CompletionEvent, OrderedLock
32
+
33
+ if TYPE_CHECKING:
34
+ import datetime
35
+ from collections.abc import MutableMapping
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class CheckpointBatcherConfig:
42
+ """Configuration for checkpoint batching behavior.
43
+
44
+ Attributes:
45
+ max_batch_size_bytes: Maximum batch size in bytes (default: 750KB)
46
+ max_batch_time_seconds: Maximum time to wait before flushing batch (default: 1.0 second)
47
+ max_batch_operations: Maximum number of operations per batch (default: unlimited)
48
+ """
49
+
50
+ max_batch_size_bytes: int = 750 * 1024 # 750KB - private readonly MAX_PAYLOAD_SIZE
51
+ max_batch_time_seconds: float = 1.0 # 1 second default
52
+ max_batch_operations: int | float = float("inf") # No operation limit by default
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class QueuedOperation:
57
+ """Wrapper for operations in the checkpoint queue.
58
+
59
+ Attributes:
60
+ operation_update: The operation update to be checkpointed, or None for empty checkpoints
61
+ completion_event: CompletionEvent for synchronous operations, or None for async operations
62
+ """
63
+
64
+ operation_update: OperationUpdate | None
65
+ completion_event: CompletionEvent | None = None
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class CheckpointedResult:
70
+ """Result of a checkpointed operation.
71
+
72
+ Set by ExecutionState.get_checkpoint_result. This is a convenience wrapper around
73
+ Operation.
74
+
75
+ Attributes:
76
+ operation (Operation): The wrapped operation for the checkpoint result.
77
+ status (OperationStatus): The status of the operation.
78
+ result (str): the result of the operation.
79
+ error (ErrorObject): the error of the operation.
80
+ """
81
+
82
+ operation: Operation | None = None
83
+ status: OperationStatus | None = None
84
+ result: str | None = None
85
+ error: ErrorObject | None = None
86
+
87
+ @classmethod
88
+ def create_from_operation(cls, operation: Operation) -> CheckpointedResult:
89
+ """Create a result from an operation."""
90
+ result: str | None = None
91
+ error: ErrorObject | None = None
92
+ match operation.operation_type:
93
+ case OperationType.STEP:
94
+ step_details = operation.step_details
95
+ result = step_details.result if step_details else None
96
+ error = step_details.error if step_details else None
97
+
98
+ case OperationType.CALLBACK:
99
+ callback_details = operation.callback_details
100
+ result = callback_details.result if callback_details else None
101
+ error = callback_details.error if callback_details else None
102
+
103
+ case OperationType.CHAINED_INVOKE:
104
+ invoke_details = operation.chained_invoke_details
105
+ result = invoke_details.result if invoke_details else None
106
+ error = invoke_details.error if invoke_details else None
107
+
108
+ case OperationType.CONTEXT:
109
+ context_details = operation.context_details
110
+ result = context_details.result if context_details else None
111
+ error = context_details.error if context_details else None
112
+
113
+ return cls(
114
+ operation=operation, status=operation.status, result=result, error=error
115
+ )
116
+
117
+ @classmethod
118
+ def create_not_found(cls) -> CheckpointedResult:
119
+ """Create a result when the checkpoint was not found."""
120
+ return cls(operation=None)
121
+
122
+ def is_existent(self) -> bool:
123
+ """Return true if a checkpoint of any type exists."""
124
+ return self.operation is not None
125
+
126
+ def is_succeeded(self) -> bool:
127
+ """Return True if the checkpointed operation is SUCCEEDED."""
128
+ op = self.operation
129
+ if not op:
130
+ return False
131
+
132
+ return op.status is OperationStatus.SUCCEEDED
133
+
134
+ def is_cancelled(self) -> bool:
135
+ if op := self.operation:
136
+ return op.status is OperationStatus.CANCELLED
137
+ return False
138
+
139
+ def is_failed(self) -> bool:
140
+ """Return True if the checkpointed operation is FAILED."""
141
+ op = self.operation
142
+ if not op:
143
+ return False
144
+
145
+ return op.status is OperationStatus.FAILED
146
+
147
+ def is_stopped(self) -> bool:
148
+ """Return True if the checkpointed operation is STOPPED"""
149
+ op = self.operation
150
+ if not op:
151
+ return False
152
+
153
+ return op.status is OperationStatus.STOPPED
154
+
155
+ def is_started(self) -> bool:
156
+ """Return True if the checkpointed operation is STARTED."""
157
+ op = self.operation
158
+ if not op:
159
+ return False
160
+ return op.status is OperationStatus.STARTED
161
+
162
+ def is_started_or_ready(self) -> bool:
163
+ """Return True if the checkpointed operation is STARTED or READY."""
164
+ op = self.operation
165
+ if not op:
166
+ return False
167
+ return op.status in {OperationStatus.STARTED, OperationStatus.READY}
168
+
169
+ def is_pending(self) -> bool:
170
+ """Return True if the checkpointed operation is PENDING."""
171
+ op = self.operation
172
+ if not op:
173
+ return False
174
+ return op.status is OperationStatus.PENDING
175
+
176
+ def is_timed_out(self) -> bool:
177
+ """Return True if the checkpointed operation is TIMED_OUT."""
178
+ op = self.operation
179
+ if not op:
180
+ return False
181
+ return op.status is OperationStatus.TIMED_OUT
182
+
183
+ def is_replay_children(self) -> bool:
184
+ op = self.operation
185
+ if not op:
186
+ return False
187
+ return op.context_details.replay_children if op.context_details else False
188
+
189
+ def raise_callable_error(self, msg: str | None = None) -> None:
190
+ if self.error is None:
191
+ err_msg = (
192
+ msg
193
+ or "Unknown error. No ErrorObject exists on the Checkpoint Operation."
194
+ )
195
+ raise CallableRuntimeError(
196
+ message=err_msg,
197
+ error_type=None,
198
+ data=None,
199
+ stack_trace=None,
200
+ )
201
+
202
+ raise self.error.to_callable_runtime_error()
203
+
204
+ def get_next_attempt_timestamp(self) -> datetime.datetime | None:
205
+ if self.operation and self.operation.step_details:
206
+ return self.operation.step_details.next_attempt_timestamp
207
+ return None
208
+
209
+
210
+ # shared so don't need to create an instance for each not found check
211
+ CHECKPOINT_NOT_FOUND = CheckpointedResult.create_not_found()
212
+
213
+
214
+ class ReplayStatus(Enum):
215
+ """Status indicating whether execution is replaying or executing new operations."""
216
+
217
+ REPLAY = "replay"
218
+ NEW = "new"
219
+
220
+
221
+ class ExecutionState:
222
+ """Get, set and maintain execution state. This is mutable. Create and check checkpoints."""
223
+
224
+ def __init__(
225
+ self,
226
+ durable_execution_arn: str,
227
+ initial_checkpoint_token: str,
228
+ operations: MutableMapping[str, Operation],
229
+ service_client: DurableServiceClient,
230
+ batcher_config: CheckpointBatcherConfig | None = None,
231
+ replay_status: ReplayStatus = ReplayStatus.NEW,
232
+ ):
233
+ self.durable_execution_arn: str = durable_execution_arn
234
+ self._current_checkpoint_token: str = initial_checkpoint_token
235
+ self.operations: MutableMapping[str, Operation] = operations
236
+ self._service_client: DurableServiceClient = service_client
237
+ self._ordered_checkpoint_lock: OrderedLock = OrderedLock()
238
+ self._operations_lock: Lock = Lock()
239
+
240
+ # Checkpoint batching configuration
241
+ self._batcher_config: CheckpointBatcherConfig = (
242
+ batcher_config or CheckpointBatcherConfig()
243
+ )
244
+
245
+ # Checkpoint batching components
246
+ self._checkpoint_queue: queue.Queue[QueuedOperation] = queue.Queue()
247
+ self._overflow_queue: queue.Queue[QueuedOperation] = queue.Queue()
248
+ self._checkpointing_stopped: threading.Event = threading.Event()
249
+ self._checkpointing_failed: CompletionEvent = CompletionEvent()
250
+
251
+ # Concurrency management for parallel operations: parent_id -> {child_operation_ids}
252
+ self._parent_to_children: dict[str, set[str]] = {}
253
+
254
+ # Operations whose parent has completed
255
+ self._parent_done: set[str] = set()
256
+
257
+ # Protects parent_to_children and parent_done
258
+ self._parent_done_lock: Lock = Lock()
259
+ self._replay_status: ReplayStatus = replay_status
260
+ self._replay_status_lock: Lock = Lock()
261
+ self._visited_operations: set[str] = set()
262
+
263
+ def fetch_paginated_operations(
264
+ self,
265
+ initial_operations: list[Operation],
266
+ checkpoint_token: str,
267
+ next_marker: str | None,
268
+ ) -> None:
269
+ """Add initial operations and fetch all paginated operations from the Durable Functions API. This method is thread_safe.
270
+
271
+ The checkpoint_token is passed explicitly as a parameter rather than using the instance variable to ensure thread safety.
272
+
273
+ Args:
274
+ initial_operations: initial operations to be added to ExecutionState
275
+ checkpoint_token: checkpoint token used to call Durable Functions API.
276
+ next_marker: a marker indicates that there are paginated operations.
277
+ """
278
+ all_operations: list[Operation] = (
279
+ initial_operations.copy() if initial_operations else []
280
+ )
281
+ while next_marker:
282
+ output: StateOutput = self._service_client.get_execution_state(
283
+ durable_execution_arn=self.durable_execution_arn,
284
+ checkpoint_token=checkpoint_token,
285
+ next_marker=next_marker,
286
+ )
287
+ all_operations.extend(output.operations)
288
+ next_marker = output.next_marker
289
+ with self._operations_lock:
290
+ self.operations.update({op.operation_id: op for op in all_operations})
291
+
292
+ def track_replay(self, operation_id: str) -> None:
293
+ """Check if operation exists with completed status; if not, transition to NEW status.
294
+
295
+ This method is called before each operation (step, wait, invoke, etc.) to determine
296
+ if we've reached the replay boundary. Once we encounter an operation that doesn't
297
+ exist or isn't completed, we transition from REPLAY to NEW status, which enables
298
+ logging for all subsequent code.
299
+
300
+ Args:
301
+ operation_id: The operation ID to check
302
+ """
303
+ with self._replay_status_lock:
304
+ if self._replay_status == ReplayStatus.REPLAY:
305
+ self._visited_operations.add(operation_id)
306
+ completed_ops = {
307
+ op_id
308
+ for op_id, op in self.operations.items()
309
+ if op.operation_type != OperationType.EXECUTION
310
+ and op.status
311
+ in {
312
+ OperationStatus.SUCCEEDED,
313
+ OperationStatus.FAILED,
314
+ OperationStatus.CANCELLED,
315
+ OperationStatus.STOPPED,
316
+ }
317
+ }
318
+ if completed_ops.issubset(self._visited_operations):
319
+ logger.debug(
320
+ "Transitioning from REPLAY to NEW status at operation %s",
321
+ operation_id,
322
+ )
323
+ self._replay_status = ReplayStatus.NEW
324
+
325
+ def is_replaying(self) -> bool:
326
+ """Check if execution is currently in replay mode.
327
+
328
+ Returns:
329
+ True if in REPLAY status, False if in NEW status
330
+ """
331
+ with self._replay_status_lock:
332
+ return self._replay_status is ReplayStatus.REPLAY
333
+
334
+ def get_checkpoint_result(self, checkpoint_id: str) -> CheckpointedResult:
335
+ """Get checkpoint result.
336
+
337
+ Note this does not invoke the Durable Functions API. It only checks
338
+ against the checkpoints currently saved in ExecutionState. The current
339
+ saved checkpoints are from InitialExecutionState as retrieved
340
+ at the start of the current execution/replay (see execution.durable_execution),
341
+ and from each create_checkpoint response.
342
+
343
+ Args:
344
+ checkpoint_id: str - id for checkpoint to retrieve.
345
+
346
+ Returns:
347
+ CheckpointedResult with is_succeeded True if the checkpoint exists and its
348
+ status is SUCCEEDED. If the checkpoint exists but its status is not
349
+ SUCCEEDED, or if the checkpoint doesn't exist, then return
350
+ CheckpointedResult with is_succeeded=False,result=None.
351
+ """
352
+ # checking status are deliberately under a lighter non-serialized lock
353
+ with self._operations_lock:
354
+ if checkpoint := self.operations.get(checkpoint_id):
355
+ return CheckpointedResult.create_from_operation(checkpoint)
356
+
357
+ return CHECKPOINT_NOT_FOUND
358
+
359
+ def create_checkpoint(
360
+ self,
361
+ operation_update: OperationUpdate | None = None,
362
+ is_sync: bool = True, # noqa: FBT001, FBT002
363
+ ) -> None:
364
+ """Create a checkpoint with optional synchronous behavior.
365
+
366
+ This method enqueues a checkpoint operation for processing by the background
367
+ batching thread. By default, the operation is synchronous (blocking) to ensure
368
+ the checkpoint is persisted before continuing. For performance-critical paths
369
+ where immediate confirmation is not required, set is_sync=False.
370
+
371
+ Synchronous checkpoints (is_sync=True, default):
372
+ - Block the caller until the checkpoint is processed by the background thread
373
+ - Ensure the checkpoint is persisted before continuing
374
+ - Safe default for correctness
375
+ - Use cases: Most operations requiring confirmation before proceeding
376
+
377
+ Asynchronous checkpoints (is_sync=False, opt-in):
378
+ - Return immediately without waiting for the checkpoint to complete
379
+ - Performance optimization for specific use cases
380
+ - Use cases: observability checkpoints, fire-and-forget operations
381
+
382
+ When to use synchronous checkpoints (is_sync=True, default):
383
+ 1. Step START with AtMostOncePerRetry semantics - prevents duplicate execution
384
+ 2. Operation completion (SUCCEED/FAIL) - ensures state persisted before returning
385
+ 3. Retry operations - ensures retry state recorded before continuing
386
+ 4. Callback START - must wait for API to generate callback ID
387
+ 5. Invoke START - ensures chained invoke recorded before proceeding
388
+ 6. Child context results - ensures results persisted before returning
389
+ 7. Large results - ensures results saved before returning to caller
390
+ 8. Wait for condition completion - ensures state recorded before proceeding
391
+ 9. Most operations - safe default
392
+
393
+ When to use asynchronous checkpoints (is_sync=False, opt-in):
394
+ 1. Step START with AtLeastOncePerRetry semantics - performance optimization
395
+ 2. Child context START - fire-and-forget for performance
396
+ 3. Wait for condition START - observability only, no blocking needed
397
+ 4. Any checkpoint where immediate confirmation is not required AND performance matters
398
+
399
+ Args:
400
+ operation_update: The checkpoint to create. If None, creates an empty
401
+ checkpoint to get a fresh checkpoint token and updated
402
+ operations list.
403
+ is_sync: If True (default), blocks until the checkpoint is processed.
404
+ If False, returns immediately without blocking for performance.
405
+
406
+ Raises:
407
+ Any exception from the background checkpoint processing will propagate
408
+ through the ThreadPoolExecutor to the main thread, terminating the Lambda.
409
+
410
+ Examples:
411
+ # Synchronous checkpoint (default, safe)
412
+ execution_state.create_checkpoint(operation_update)
413
+
414
+ # Explicit synchronous checkpoint
415
+ execution_state.create_checkpoint(operation_update, is_sync=True)
416
+
417
+ # Asynchronous checkpoint (opt-in for performance)
418
+ execution_state.create_checkpoint(operation_update, is_sync=False)
419
+
420
+ # Empty checkpoint (sync by default)
421
+ execution_state.create_checkpoint()
422
+
423
+ # Empty checkpoint (async for performance)
424
+ execution_state.create_checkpoint(is_sync=False)
425
+ """
426
+ # if this is CONTEXT complete, mark incomplete descendants as orphans so the children can't complete after the parent
427
+ if operation_update is not None:
428
+ # Use single lock to coordinate completion and checkpoint validation
429
+ with self._parent_done_lock:
430
+ # Build parent-to-children map as operations are created
431
+ if operation_update.parent_id:
432
+ if operation_update.parent_id not in self._parent_to_children:
433
+ self._parent_to_children[operation_update.parent_id] = set()
434
+ self._parent_to_children[operation_update.parent_id].add(
435
+ operation_update.operation_id
436
+ )
437
+
438
+ # Handle CONTEXT completion - mark descendants while holding lock
439
+ if (
440
+ operation_update.operation_type == OperationType.CONTEXT
441
+ and operation_update.action
442
+ in {OperationAction.SUCCEED, OperationAction.FAIL}
443
+ ):
444
+ self._mark_orphans(operation_update.operation_id)
445
+
446
+ # Check if this operation's parent is done
447
+ if operation_update.operation_id in self._parent_done:
448
+ logger.debug(
449
+ "Rejecting checkpoint for operation %s - parent is done",
450
+ operation_update.operation_id,
451
+ )
452
+ return
453
+
454
+ # Check if background checkpointing has failed
455
+ if self._checkpointing_failed.is_set():
456
+ # This will raise the stored BackgroundThreadError
457
+ self._checkpointing_failed.wait()
458
+
459
+ # Conditionally create completion event based on is_sync parameter
460
+ completion_event: CompletionEvent | None = (
461
+ CompletionEvent() if is_sync else None
462
+ )
463
+
464
+ # Create wrapper object for queue
465
+ queued_op = QueuedOperation(operation_update, completion_event)
466
+
467
+ # Enqueue the wrapper object (operation_update can be None for empty checkpoints)
468
+ self._checkpoint_queue.put(queued_op)
469
+
470
+ # Conditionally wait for completion based on is_sync parameter
471
+ if is_sync:
472
+ logger.debug("Enqueued checkpoint operation for synchronous processing")
473
+ if completion_event is None: # pragma: no cover
474
+ # this shouldn't ever be possible
475
+ msg: str = "completion_event must be set for synchronous execution"
476
+ raise DurableExecutionsError(msg)
477
+
478
+ # Wait for completion - will raise BackgroundThreadError if background thread fails
479
+ completion_event.wait()
480
+ else:
481
+ logger.debug("Enqueued checkpoint operation for asynchronous processing")
482
+
483
+ def create_checkpoint_sync(
484
+ self,
485
+ operation_update: OperationUpdate | None = None,
486
+ ) -> None:
487
+ """Create a synchronous checkpoint that raises original errors instead of BackgroundThreadError.
488
+
489
+ This method is identical to create_checkpoint(is_sync=True) except that if the background
490
+ checkpoint processing fails, it raises the original exception directly instead of wrapping
491
+ it in a BackgroundThreadError.
492
+
493
+ This is useful in execution contexts where you want the original checkpoint error to
494
+ propagate (e.g., CheckpointError, RuntimeError) rather than the wrapped BackgroundThreadError.
495
+ The method always blocks until the checkpoint is processed.
496
+
497
+ Args:
498
+ operation_update: The checkpoint to create. If None, creates an empty checkpoint.
499
+
500
+ Raises:
501
+ The original exception from the background checkpoint processing if it fails,
502
+ unwrapped from BackgroundThreadError (e.g., CheckpointError, RuntimeError).
503
+
504
+ Example:
505
+ # Instead of getting BackgroundThreadError wrapping a CheckpointError:
506
+ execution_state.create_checkpoint_sync(operation_update)
507
+ # Raises CheckpointError directly
508
+ """
509
+ try:
510
+ self.create_checkpoint(operation_update, is_sync=True)
511
+ except BackgroundThreadError as bg_error:
512
+ # Background checkpoint system failed - unwrap the original error
513
+ logger.exception("Checkpoint processing failed - unwrapping original error")
514
+ self.stop_checkpointing()
515
+ # Raise the original exception unwrapped
516
+ raise bg_error.source_exception from bg_error
517
+
518
+ def _mark_orphans(self, context_id: str) -> None:
519
+ """Mark all descendants (direct and transitive) as orphaned.
520
+
521
+ This method uses BFS (Breadth-First Search) to recursively collect all
522
+ descendants of the given context operation and marks them as orphaned.
523
+ Once marked, these operations will be rejected if they attempt to checkpoint.
524
+
525
+ Must be called while holding _parent_done_lock.
526
+
527
+ Args:
528
+ context_id: The operation ID of the CONTEXT that has completed
529
+ """
530
+ # Collect all descendants recursively using BFS
531
+ all_descendants = set()
532
+ # Start with root
533
+ to_process: set[str] = {context_id}
534
+
535
+ while to_process:
536
+ current_id = to_process.pop()
537
+
538
+ # Skip if already processed (avoid cycles, though shouldn't happen)
539
+ if current_id in all_descendants:
540
+ continue
541
+
542
+ all_descendants.add(current_id)
543
+
544
+ # Add all direct children to processing queue
545
+ direct_children = self._parent_to_children.get(current_id, set())
546
+ to_process.update(direct_children)
547
+
548
+ # Remove the root itself (we only want descendants)
549
+ all_descendants.discard(context_id)
550
+
551
+ # Mark all descendants as orphaned
552
+ self._parent_done.update(all_descendants)
553
+ logger.debug(
554
+ "Marked %d descendants as parent-done for context %s",
555
+ len(all_descendants),
556
+ context_id,
557
+ )
558
+
559
+ def checkpoint_batches_forever(self) -> None:
560
+ """Single background thread that batches operations and processes results.
561
+
562
+ Runs until shutdown is signaled. This method processes checkpoint operations
563
+ in batches, makes API calls to persist them, and updates the execution state
564
+ with the results.
565
+
566
+ The method maintains the checkpoint token locally and updates it after each
567
+ successful batch processing. It continues running until stop_checkpointing()
568
+ is called.
569
+
570
+ Note: When shutdown is signaled, only non-essential async checkpoints may remain
571
+ in the queue. All critical synchronous checkpoints (SUCCEED, FAIL, etc.) will
572
+ have already completed because the main thread blocks on them. Therefore, we
573
+ don't need to drain the queue - the Lambda timeout will handle cleanup.
574
+
575
+ Raises:
576
+ Any exception from the service client checkpoint call will propagate naturally,
577
+ terminating the background thread and signaling an error to the main thread.
578
+ """
579
+ # Keep checkpoint token as local variable in the loop
580
+ current_checkpoint_token: str = self._current_checkpoint_token
581
+
582
+ while not self._checkpointing_stopped.is_set():
583
+ # Collect operations into a batch
584
+ batch: list[QueuedOperation] = self._collect_checkpoint_batch()
585
+
586
+ if batch:
587
+ # Extract OperationUpdates from QueuedOperations for API call
588
+ updates: list[OperationUpdate] = [
589
+ q.operation_update for q in batch if q.operation_update is not None
590
+ ]
591
+
592
+ logger.debug(
593
+ "Processing checkpoint batch with %d operations (%d non-empty)",
594
+ len(batch),
595
+ len(updates),
596
+ )
597
+
598
+ try:
599
+ # Make API call with batched operations
600
+ output: CheckpointOutput = self._service_client.checkpoint(
601
+ durable_execution_arn=self.durable_execution_arn,
602
+ checkpoint_token=current_checkpoint_token,
603
+ updates=updates,
604
+ client_token=None,
605
+ )
606
+
607
+ logger.debug("Checkpoint batch processed successfully")
608
+
609
+ # Signal completion for any synchronous operations
610
+ for queued_op in batch:
611
+ if queued_op.completion_event is not None:
612
+ queued_op.completion_event.set()
613
+
614
+ # Update local token for next iteration
615
+ current_checkpoint_token = output.checkpoint_token
616
+
617
+ # Fetch new operations from the API
618
+ self.fetch_paginated_operations(
619
+ output.new_execution_state.operations,
620
+ output.checkpoint_token,
621
+ output.new_execution_state.next_marker,
622
+ )
623
+ except Exception as e:
624
+ # Checkpoint failed - wake all blocked threads so they can raise error
625
+ # Drain both queues and signal all completion events
626
+ logger.exception("Checkpoint batch processing failed")
627
+ bg_error: BackgroundThreadError = BackgroundThreadError(
628
+ "Checkpoint creation failed", e
629
+ )
630
+
631
+ # FIFO: although at this point order not really import any anymore
632
+ # Signal completion events for the failed batch
633
+ for queued_op in batch:
634
+ if queued_op.completion_event is not None:
635
+ queued_op.completion_event.set(bg_error)
636
+
637
+ # overflow 1st: although at this point order not really import any anymore
638
+ while not self._overflow_queue.empty():
639
+ try:
640
+ item = self._overflow_queue.get_nowait()
641
+ if item.completion_event:
642
+ item.completion_event.set(bg_error)
643
+ except queue.Empty:
644
+ break
645
+
646
+ # finally Wake all blocked threads in main queue
647
+ while not self._checkpoint_queue.empty():
648
+ try:
649
+ item = self._checkpoint_queue.get_nowait()
650
+ if item.completion_event:
651
+ item.completion_event.set(bg_error)
652
+ except queue.Empty:
653
+ break
654
+
655
+ # Set the failure event so future checkpoint attempts fail immediately
656
+ self._checkpointing_failed.set(bg_error)
657
+
658
+ # Exit the loop - error has been signaled to main thread via completion events
659
+ break
660
+
661
+ logger.debug("Background checkpoint processing stopped")
662
+
663
+ def stop_checkpointing(self) -> None:
664
+ """Signal background thread to stop checkpointing.
665
+
666
+ This method sets the checkpointing stopped event, which signals the background
667
+ thread to exit. Any remaining async checkpoints in the queue are non-essential
668
+ (observability only) and will be abandoned. All critical synchronous checkpoints
669
+ will have already completed before this is called.
670
+ """
671
+ logger.debug("Signaling background thread to stop checkpointing")
672
+ self._checkpointing_stopped.set()
673
+
674
+ def _collect_checkpoint_batch(self) -> list[QueuedOperation]:
675
+ """Collect multiple checkpoint operations into a batch for API efficiency.
676
+
677
+ Processes overflow queue first to maintain FIFO order, then collects from main queue.
678
+ Respects configured size, time, and operation count limits. Blocks for the first
679
+ operation if queues are empty, then collects additional operations within the time
680
+ window.
681
+
682
+ Returns:
683
+ List of QueuedOperation objects ready for batch processing. Returns empty list
684
+ if no operations are available.
685
+ """
686
+ batch: list[QueuedOperation] = []
687
+ total_size = 0
688
+
689
+ # First, drain overflow queue (FIFO order preserved)
690
+ try:
691
+ while len(batch) < self._batcher_config.max_batch_operations:
692
+ overflow_op = self._overflow_queue.get_nowait()
693
+ op_size = self._calculate_operation_size(overflow_op)
694
+
695
+ if total_size + op_size > self._batcher_config.max_batch_size_bytes:
696
+ # Put back and stop
697
+ self._overflow_queue.put(overflow_op)
698
+ break
699
+
700
+ batch.append(overflow_op)
701
+ total_size += op_size
702
+ except queue.Empty:
703
+ pass
704
+
705
+ # If batch is empty, get first operation from main queue
706
+ if not batch:
707
+ # Block for first operation, checking stop signal periodically
708
+ while not self._checkpointing_stopped.is_set():
709
+ try:
710
+ first_op = self._checkpoint_queue.get(
711
+ timeout=0.1
712
+ ) # Check stop signal every 100ms
713
+ self._checkpoint_queue.task_done()
714
+ batch.append(first_op)
715
+ total_size += self._calculate_operation_size(first_op)
716
+ break
717
+ except queue.Empty:
718
+ continue
719
+
720
+ # If stopped and no operation retrieved, return empty batch
721
+ if not batch:
722
+ return batch
723
+
724
+ # Start batching window using configured time
725
+ batch_deadline = time.time() + self._batcher_config.max_batch_time_seconds
726
+
727
+ # Collect additional operations within the time window
728
+ while (
729
+ time.time() < batch_deadline
730
+ and len(batch) < self._batcher_config.max_batch_operations
731
+ and not self._checkpointing_stopped.is_set()
732
+ ):
733
+ remaining_time = min(
734
+ batch_deadline - time.time(),
735
+ 0.1, # Check stop signal every 100ms
736
+ )
737
+
738
+ if remaining_time <= 0:
739
+ break
740
+
741
+ try:
742
+ additional_op = self._checkpoint_queue.get(timeout=remaining_time)
743
+ self._checkpoint_queue.task_done()
744
+ op_size = self._calculate_operation_size(additional_op)
745
+
746
+ # Check if adding this operation would exceed size limit
747
+ if total_size + op_size > self._batcher_config.max_batch_size_bytes:
748
+ # Put in overflow queue for next batch
749
+ self._overflow_queue.put(additional_op)
750
+ logger.debug(
751
+ "Batch size limit reached, moving operation to overflow queue"
752
+ )
753
+ break
754
+
755
+ batch.append(additional_op)
756
+ total_size += op_size
757
+
758
+ except queue.Empty:
759
+ break
760
+
761
+ logger.debug(
762
+ "Collected batch of %d operations, total size: %d bytes",
763
+ len(batch),
764
+ total_size,
765
+ )
766
+ return batch
767
+
768
+ @staticmethod
769
+ def _calculate_operation_size(queued_op: QueuedOperation) -> int:
770
+ """Calculate the serialized size of a queued operation for batching limits.
771
+
772
+ Uses JSON serialization to estimate the size of the operation update. Empty
773
+ checkpoints (None operation_update) have zero size.
774
+
775
+ Args:
776
+ queued_op: The queued operation to calculate size for
777
+
778
+ Returns:
779
+ Size in bytes of the serialized operation, or 0 for empty checkpoints
780
+ """
781
+ # Empty checkpoints have no size
782
+ if queued_op.operation_update is None:
783
+ return 0
784
+
785
+ # Use JSON serialization to estimate size
786
+ serialized = json.dumps(queued_op.operation_update.to_dict()).encode("utf-8")
787
+ return len(serialized)
788
+
789
+ def close(self):
790
+ self.stop_checkpointing()