airbyte_cdk.sources.declarative.incremental

 1#
 2# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
 3#
 4
 5from airbyte_cdk.sources.declarative.incremental.concurrent_partition_cursor import (
 6    ConcurrentCursorFactory,
 7    ConcurrentPerPartitionCursor,
 8)
 9from airbyte_cdk.sources.declarative.incremental.sync_token_cursor import SyncTokenCursor
10
11__all__ = [
12    "ConcurrentCursorFactory",
13    "ConcurrentPerPartitionCursor",
14    "SyncTokenCursor",
15]
class ConcurrentCursorFactory:
 96class ConcurrentCursorFactory:
 97    def __init__(self, create_function: Callable[..., ConcurrentCursor]):
 98        self._create_function = create_function
 99
100    def create(
101        self, stream_state: Mapping[str, Any], runtime_lookback_window: Optional[timedelta]
102    ) -> ConcurrentCursor:
103        return self._create_function(
104            stream_state=stream_state, runtime_lookback_window=runtime_lookback_window
105        )
ConcurrentCursorFactory( create_function: Callable[..., airbyte_cdk.ConcurrentCursor])
97    def __init__(self, create_function: Callable[..., ConcurrentCursor]):
98        self._create_function = create_function
def create( self, stream_state: Mapping[str, Any], runtime_lookback_window: Optional[datetime.timedelta]) -> airbyte_cdk.ConcurrentCursor:
100    def create(
101        self, stream_state: Mapping[str, Any], runtime_lookback_window: Optional[timedelta]
102    ) -> ConcurrentCursor:
103        return self._create_function(
104            stream_state=stream_state, runtime_lookback_window=runtime_lookback_window
105        )
class ConcurrentPerPartitionCursor(airbyte_cdk.sources.streams.concurrent.cursor.Cursor):
108class ConcurrentPerPartitionCursor(Cursor):
109    """
110    Manages state per partition when a stream has many partitions, preventing data loss or duplication.
111
112    Attributes:
113        DEFAULT_MAX_PARTITIONS_NUMBER (int): Maximum number of partitions to retain in memory (default is 10,000). This limit needs to be higher than the number of threads we might enqueue (which is represented by ThreadPoolManager.DEFAULT_MAX_QUEUE_SIZE). If not, we could have partitions that have been generated and submitted to the ThreadPool but got deleted from the ConcurrentPerPartitionCursor and when closing them, it will generate KeyError.
114
115    - **Partition Limitation Logic**
116      Ensures the number of tracked partitions does not exceed the specified limit to prevent memory overuse. Oldest partitions are removed when the limit is reached.
117
118    - **Global Cursor Fallback**
119      New partitions use global state as the initial state to progress the state for deleted or new partitions. The history data added after the initial sync will be missing.
120
121    CurrentPerPartitionCursor expects the state of the ConcurrentCursor to follow the format {cursor_field: cursor_value}.
122    """
123
124    DEFAULT_MAX_PARTITIONS_NUMBER = 25_000
125    SWITCH_TO_GLOBAL_LIMIT = 10_000
126    # Minimum number of seconds between two state messages emitted when a partition closes.
127    STATE_EMIT_INTERVAL_SECONDS: float = 600
128    _NO_STATE: Mapping[str, Any] = {}
129    _NO_CURSOR_STATE: Mapping[str, Any] = {}
130    _GLOBAL_STATE_KEY = "state"
131    _PERPARTITION_STATE_KEY = "states"
132    _IS_PARTITION_DUPLICATION_LOGGED = False
133    _PARENT_STATE = 0
134    _GENERATION_SEQUENCE = 1
135
136    def __init__(
137        self,
138        cursor_factory: ConcurrentCursorFactory,
139        partition_router: PartitionRouter,
140        stream_name: str,
141        stream_namespace: Optional[str],
142        stream_state: Any,
143        message_repository: MessageRepository,
144        connector_state_manager: ConnectorStateManager,
145        connector_state_converter: AbstractStreamStateConverter,
146        cursor_field: CursorField,
147        use_global_cursor: bool = False,
148        attempt_to_create_cursor_if_not_provided: bool = False,
149    ) -> None:
150        self._global_cursor: Optional[StreamState] = {}
151        self._stream_name = stream_name
152        self._stream_namespace = stream_namespace
153        self._message_repository = message_repository
154        self._connector_state_manager = connector_state_manager
155        self._connector_state_converter = connector_state_converter
156        self._cursor_field = cursor_field
157
158        self._cursor_factory = cursor_factory  # self._cursor_factory is flagged as private but is used in model_to_component_factory to ease pagination reset instantiation
159        self._partition_router = partition_router
160
161        # The dict is ordered to ensure that once the maximum number of partitions is reached,
162        # the oldest partitions can be efficiently removed, maintaining the most recent partitions.
163        self._cursor_per_partition: OrderedDict[str, ConcurrentCursor] = OrderedDict()
164        self._semaphore_per_partition: OrderedDict[str, threading.Semaphore] = OrderedDict()
165
166        # Parent-state tracking: store each partition’s parent state in creation order
167        self._partition_parent_state_map: OrderedDict[str, tuple[Mapping[str, Any], int]] = (
168            OrderedDict()
169        )
170        self._parent_state: Optional[StreamState] = None
171
172        # Tracks when the last slice for partition is emitted
173        self._partitions_done_generating_stream_slices: set[str] = set()
174        # Used to track the index of partitions that are not closed yet
175        self._processing_partitions_indexes: List[int] = list()
176        self._generated_partitions_count: int = 0
177        # Dictionary to map partition keys to their index
178        self._partition_key_to_index: dict[str, int] = {}
179
180        self._lock = threading.Lock()
181        self._request_window_splitting_cursor: Optional[ConcurrentCursor] = None
182        self._lookback_window: int = 0
183        self._new_global_cursor: Optional[StreamState] = None
184        self._number_of_partitions: int = 0
185        self._use_global_cursor: bool = use_global_cursor
186        self._partition_serializer = PerPartitionKeySerializer()
187
188        # Track the last time a state message was emitted
189        self._last_emission_time: float = 0.0
190        self._timer = Timer()
191
192        self._set_initial_state(stream_state)
193
194        # FIXME this is a temporary field the time of the migration from declarative cursors to concurrent ones
195        self._attempt_to_create_cursor_if_not_provided = attempt_to_create_cursor_if_not_provided
196        self._synced_some_data = False
197        self._finished_generating_slices = False
198        self._logged_regarding_datetime_format_error = False
199
200    @property
201    def cursor_field(self) -> CursorField:
202        return self._cursor_field
203
204    @property
205    def partition_router(self) -> PartitionRouter:
206        return self._partition_router
207
208    @property
209    def state(self) -> MutableMapping[str, Any]:
210        state: dict[str, Any] = {"use_global_cursor": self._use_global_cursor}
211        if not self._use_global_cursor:
212            states = []
213            for partition_tuple, cursor in self._cursor_per_partition.items():
214                if cursor.state:
215                    states.append(
216                        {
217                            "partition": self._to_dict(partition_tuple),
218                            "cursor": copy.deepcopy(cursor.state),
219                        }
220                    )
221            state[self._PERPARTITION_STATE_KEY] = states
222
223        if self._global_cursor:
224            state[self._GLOBAL_STATE_KEY] = self._global_cursor
225        if self._lookback_window is not None:
226            state["lookback_window"] = self._lookback_window
227        if self._parent_state is not None:
228            state["parent_state"] = self._parent_state
229        return state
230
231    def close_partition(self, partition: Partition) -> None:
232        # Attempt to retrieve the stream slice
233        stream_slice: Optional[StreamSlice] = partition.to_slice()  # type: ignore[assignment]
234
235        # Ensure stream_slice is not None
236        if stream_slice is None:
237            raise ValueError("stream_slice cannot be None")
238
239        partition_key = self._to_partition_key(stream_slice.partition)
240        with self._lock:
241            self._semaphore_per_partition[partition_key].acquire()
242            if not self._use_global_cursor:
243                cursor = self._cursor_per_partition[partition_key]
244                cursor.close_partition(partition=partition)
245                if (
246                    partition_key in self._partitions_done_generating_stream_slices
247                    and self._semaphore_per_partition[partition_key]._value == 0
248                ):
249                    self._update_global_cursor(cursor.state[self.cursor_field.cursor_field_key])
250
251            # Clean up the partition if it is fully processed
252            self._cleanup_if_done(partition_key)
253
254            self._check_and_update_parent_state()
255
256            self._emit_state_message()
257
258    def _check_and_update_parent_state(self) -> None:
259        last_closed_state = None
260
261        while self._partition_parent_state_map:
262            earliest_key, (candidate_state, candidate_seq) = next(
263                iter(self._partition_parent_state_map.items())
264            )
265
266            # if any partition that started <= candidate_seq is still open, we must wait
267            if (
268                self._processing_partitions_indexes
269                and self._processing_partitions_indexes[0] <= candidate_seq
270            ):
271                break
272
273            # safe to pop
274            self._partition_parent_state_map.popitem(last=False)
275            last_closed_state = candidate_state
276
277        if last_closed_state is not None:
278            self._parent_state = last_closed_state
279
280    def ensure_at_least_one_state_emitted(self) -> None:
281        """
282        The platform expects at least one state message on successful syncs. Hence, whatever happens, we expect this method to be
283        called.
284
285        If the stream did not complete (a partition was never closed, or slice generation stopped early), the global cursor is not
286        advanced, because partitions that were never generated have not been read up to it. If the state then holds no
287        checkpoint, nothing is emitted. Such a state records no progress, but it is not empty, so the next attempt would treat
288        the stream as already synced once: a StateDelegatingStream would switch to its incremental stream and never read the
289        slices this attempt missed. This covers global-cursor streams; in per-partition mode the cursor of every generated
290        partition reports its start value, so the state is still emitted.
291
292        If slice generation stopped early, the parent state is not refreshed from the partition router: the router may already have closed a parent slice whose last child slice was never generated, so only the parent state recorded by `_check_and_update_parent_state` for closed child partitions is kept.
293        """
294        all_partitions_closed = not any(
295            semaphore_item[1]._value for semaphore_item in self._semaphore_per_partition.items()
296        )
297        stream_completed = all_partitions_closed and self._finished_generating_slices
298        if all_partitions_closed:
299            if self._synced_some_data and stream_completed:
300                # we only update those if we actually synced some data
301                self._global_cursor = self._new_global_cursor
302                self._lookback_window = self._timer.finish()
303            if stream_completed:
304                self._parent_state = self._partition_router.get_stream_state()
305        if not stream_completed and not self._has_checkpoint():
306            return
307        self._emit_state_message(throttle=False)
308
309    def _has_checkpoint(self) -> bool:
310        state = self.state
311        return bool(
312            state.get(self._GLOBAL_STATE_KEY)
313            or state.get(self._PERPARTITION_STATE_KEY)
314            or state.get("parent_state")
315        )
316
317    def _throttle_state_message(self) -> Optional[float]:
318        """
319        Throttles the state message emission to once every `STATE_EMIT_INTERVAL_SECONDS` seconds.
320        """
321        current_time = time.time()
322        if current_time - self._last_emission_time <= self.STATE_EMIT_INTERVAL_SECONDS:
323            return None
324        return current_time
325
326    def _emit_state_message(self, throttle: bool = True) -> None:
327        if throttle:
328            current_time = self._throttle_state_message()
329            if current_time is None:
330                return
331            self._last_emission_time = current_time
332            # Skip state emit for global cursor if parent state is empty
333            if self._use_global_cursor and not self._parent_state:
334                return
335
336        self._connector_state_manager.update_state_for_stream(
337            self._stream_name,
338            self._stream_namespace,
339            self.state,
340        )
341        state_message = self._connector_state_manager.create_state_message(
342            self._stream_name, self._stream_namespace
343        )
344        self._message_repository.emit_message(state_message)
345
346    def stream_slices(self) -> Iterable[StreamSlice]:
347        if self._timer.is_running():
348            raise RuntimeError("stream_slices has been executed more than once.")
349
350        slices = self._partition_router.stream_slices()
351        self._timer.start()
352        for partition, last, parent_state in iterate_with_last_flag_and_state(
353            slices, self._partition_router.get_stream_state
354        ):
355            yield from self._generate_slices_from_partition(partition, parent_state)
356        self._finished_generating_slices = True
357
358    def _generate_slices_from_partition(
359        self, partition: StreamSlice, parent_state: Mapping[str, Any]
360    ) -> Iterable[StreamSlice]:
361        # Ensure the maximum number of partitions is not exceeded
362        self._ensure_partition_limit()
363
364        partition_key = self._to_partition_key(partition.partition)
365
366        cursor = self._cursor_per_partition.get(self._to_partition_key(partition.partition))
367        if not cursor:
368            cursor = self._create_cursor(
369                self._global_cursor,
370                self._lookback_window if self._global_cursor else 0,
371            )
372            with self._lock:
373                self._number_of_partitions += 1
374                self._cursor_per_partition[partition_key] = cursor
375
376        if partition_key in self._semaphore_per_partition:
377            if not self._IS_PARTITION_DUPLICATION_LOGGED:
378                logger.warning(f"Partition duplication detected for stream {self._stream_name}")
379                self._IS_PARTITION_DUPLICATION_LOGGED = True
380            return
381        else:
382            self._semaphore_per_partition[partition_key] = threading.Semaphore(0)
383
384        with self._lock:
385            seq = self._generated_partitions_count
386            self._generated_partitions_count += 1
387            self._processing_partitions_indexes.append(seq)
388            self._partition_key_to_index[partition_key] = seq
389
390            if (
391                len(self._partition_parent_state_map) == 0
392                or self._partition_parent_state_map[
393                    next(reversed(self._partition_parent_state_map))
394                ][self._PARENT_STATE]
395                != parent_state
396            ):
397                self._partition_parent_state_map[partition_key] = (deepcopy(parent_state), seq)
398
399        for cursor_slice, is_last_slice, _ in iterate_with_last_flag_and_state(
400            cursor.stream_slices(),
401            lambda: None,
402        ):
403            self._semaphore_per_partition[partition_key].release()
404            if is_last_slice:
405                self._partitions_done_generating_stream_slices.add(partition_key)
406            yield StreamSlice(
407                partition=partition, cursor_slice=cursor_slice, extra_fields=partition.extra_fields
408            )
409
410    def _ensure_partition_limit(self) -> None:
411        """
412        Ensure the maximum number of partitions does not exceed the predefined limit.
413
414        Steps:
415        1. Attempt to remove partitions that are marked as finished in `_finished_partitions`.
416           These partitions are considered processed and safe to delete.
417        2. If the limit is still exceeded and no finished partitions are available for removal,
418           remove the oldest partition unconditionally. We expect failed partitions to be removed.
419
420        Logging:
421        - Logs a warning each time a partition is removed, indicating whether it was finished
422          or removed due to being the oldest.
423        """
424        if not self._use_global_cursor and self.limit_reached():
425            logger.info(
426                f"Exceeded the 'SWITCH_TO_GLOBAL_LIMIT' of {self.SWITCH_TO_GLOBAL_LIMIT}. "
427                f"Switching to global cursor for {self._stream_name}."
428            )
429            self._use_global_cursor = True
430
431        with self._lock:
432            while len(self._cursor_per_partition) > self.DEFAULT_MAX_PARTITIONS_NUMBER - 1:
433                # Try removing finished partitions first
434                for partition_key in list(self._cursor_per_partition.keys()):
435                    if partition_key not in self._partition_key_to_index:
436                        oldest_partition = self._cursor_per_partition.pop(
437                            partition_key
438                        )  # Remove the oldest partition
439                        logger.debug(
440                            f"The maximum number of partitions has been reached. Dropping the oldest finished partition: {oldest_partition}. Over limit: {self._number_of_partitions - self.DEFAULT_MAX_PARTITIONS_NUMBER}."
441                        )
442                        break
443                else:
444                    # If no finished partitions can be removed, fall back to removing the oldest partition
445                    oldest_partition = self._cursor_per_partition.popitem(last=False)[
446                        1
447                    ]  # Remove the oldest partition
448                    logger.warning(
449                        f"The maximum number of partitions has been reached. Dropping the oldest partition: {oldest_partition}. Over limit: {self._number_of_partitions - self.DEFAULT_MAX_PARTITIONS_NUMBER}."
450                    )
451
452    def _set_initial_state(self, stream_state: StreamState) -> None:
453        """
454        Initialize the cursor's state using the provided `stream_state`.
455
456        This method supports global and per-partition state initialization.
457
458        - **Global State**: If `states` is missing, the `state` is treated as global and applied to all partitions.
459          The `global state` holds a single cursor position representing the latest processed record across all partitions.
460
461        - **Lookback Window**: Configured via `lookback_window`, it defines the period (in seconds) for reprocessing records.
462          This ensures robustness in case of upstream data delays or reordering. If not specified, it defaults to 0.
463
464        - **Per-Partition State**: If `states` is present, each partition's cursor state is initialized separately.
465
466        - **Parent State**: (if available) Used to initialize partition routers based on parent streams.
467
468        Args:
469            stream_state (StreamState): The state of the streams to be set. The format of the stream state should be:
470                {
471                    "states": [
472                        {
473                            "partition": {
474                                "partition_key": "value"
475                            },
476                            "cursor": {
477                                "last_updated": "2023-05-27T00:00:00Z"
478                            }
479                        }
480                    ],
481                    "state": {
482                        "last_updated": "2023-05-27T00:00:00Z"
483                    },
484                    lookback_window: 10,
485                    "parent_state": {
486                        "parent_stream_name": {
487                            "last_updated": "2023-05-27T00:00:00Z"
488                        }
489                    }
490                }
491        """
492        if not stream_state:
493            return
494
495        if (
496            self._PERPARTITION_STATE_KEY not in stream_state
497            and self._GLOBAL_STATE_KEY not in stream_state
498        ):
499            # We assume that `stream_state` is in a global format that can be applied to all partitions.
500            # Example: {"global_state_format_key": "global_state_format_value"}
501            self._set_global_state(stream_state)
502
503        else:
504            self._use_global_cursor = stream_state.get("use_global_cursor", False)
505
506            self._lookback_window = int(stream_state.get("lookback_window", 0))
507
508            for state in stream_state.get(self._PERPARTITION_STATE_KEY, []):
509                self._number_of_partitions += 1
510                self._cursor_per_partition[self._to_partition_key(state["partition"])] = (
511                    self._create_cursor(state["cursor"])
512                )
513
514            # set default state for missing partitions if it is per partition with fallback to global
515            if self._GLOBAL_STATE_KEY in stream_state:
516                self._set_global_state(stream_state[self._GLOBAL_STATE_KEY])
517
518        # Set initial parent state
519        if stream_state.get("parent_state"):
520            self._parent_state = stream_state["parent_state"]
521
522    def _set_global_state(self, stream_state: Mapping[str, Any]) -> None:
523        """
524        Initializes the global cursor state from the provided stream state.
525
526        If the cursor field key is present in the stream state, its value is parsed,
527        formatted, and stored as the global cursor. This ensures consistency in state
528        representation across partitions.
529        """
530        if self.cursor_field.cursor_field_key in stream_state:
531            global_state_value = stream_state[self.cursor_field.cursor_field_key]
532            final_format_global_state_value = self._connector_state_converter.output_format(
533                self._connector_state_converter.parse_value(global_state_value)
534            )
535
536            fixed_global_state = {
537                self.cursor_field.cursor_field_key: final_format_global_state_value
538            }
539
540            self._global_cursor = deepcopy(fixed_global_state)
541            self._new_global_cursor = deepcopy(fixed_global_state)
542
543    def observe(self, record: Record) -> None:
544        if not record.associated_slice:
545            raise ValueError(
546                "Invalid state as stream slices that are emitted should refer to an existing cursor"
547            )
548
549        # if the current record has no cursor value, we cannot meaningfully update the state based on it, so there is nothing more to do
550        try:
551            record_cursor_value = self._cursor_field.extract_value(record)
552        except ValueError:
553            return
554
555        try:
556            record_cursor = self._connector_state_converter.output_format(
557                self._connector_state_converter.parse_value(record_cursor_value)
558            )
559        except ValueError as exception:
560            if not self._logged_regarding_datetime_format_error:
561                logger.warning(
562                    "Skipping cursor update for stream '%s': failed to parse cursor field '%s' value %r: %s",
563                    self._stream_name,
564                    self._cursor_field.cursor_field_key,
565                    record_cursor_value,
566                    exception,
567                )
568                self._logged_regarding_datetime_format_error = True
569            return
570
571        self._synced_some_data = True
572        self._update_global_cursor(record_cursor)
573        if not self._use_global_cursor:
574            self._cursor_per_partition[
575                self._to_partition_key(record.associated_slice.partition)
576            ].observe(record)
577
578    def _update_global_cursor(self, value: Any) -> None:
579        if (
580            self._new_global_cursor is None
581            or self._new_global_cursor[self.cursor_field.cursor_field_key] < value
582        ):
583            self._new_global_cursor = {self.cursor_field.cursor_field_key: copy.deepcopy(value)}
584
585    def _cleanup_if_done(self, partition_key: str) -> None:
586        """
587        Free every in-memory structure that belonged to a completed partition:
588        cursor, semaphore, flag inside `_finished_partitions`
589        """
590        if not (
591            partition_key in self._partitions_done_generating_stream_slices
592            and self._semaphore_per_partition[partition_key]._value == 0
593        ):
594            return
595
596        self._semaphore_per_partition.pop(partition_key, None)
597        self._partitions_done_generating_stream_slices.discard(partition_key)
598
599        seq = self._partition_key_to_index.pop(partition_key)
600        self._processing_partitions_indexes.remove(seq)
601
602        logger.debug(f"Partition {partition_key} fully processed and cleaned up.")
603
604    def _to_partition_key(self, partition: Mapping[str, Any]) -> str:
605        return self._partition_serializer.to_partition_key(partition)
606
607    def _to_dict(self, partition_key: str) -> Mapping[str, Any]:
608        return self._partition_serializer.to_partition(partition_key)
609
610    def _create_cursor(
611        self, cursor_state: Any, runtime_lookback_window: int = 0
612    ) -> ConcurrentCursor:
613        cursor = self._cursor_factory.create(
614            stream_state=deepcopy(cursor_state),
615            runtime_lookback_window=timedelta(seconds=runtime_lookback_window),
616        )
617        return cursor
618
619    def should_be_synced(self, record: Record) -> bool:
620        return self._get_cursor(record).should_be_synced(record)
621
622    def _get_cursor(self, record: Record) -> ConcurrentCursor:
623        if not record.associated_slice:
624            raise ValueError(
625                "Invalid state as stream slices that are emitted should refer to an existing cursor"
626            )
627
628        if self._use_global_cursor:
629            return self._create_cursor(
630                self._global_cursor,
631                self._lookback_window if self._global_cursor else 0,
632            )
633
634        partition_key = self._to_partition_key(record.associated_slice.partition)
635        if (
636            partition_key not in self._cursor_per_partition
637            and not self._attempt_to_create_cursor_if_not_provided
638        ):
639            raise ValueError(
640                "Invalid state as stream slices that are emitted should refer to an existing cursor"
641            )
642        elif partition_key not in self._cursor_per_partition:
643            return self._create_cursor(
644                self._global_cursor,
645                self._lookback_window if self._global_cursor else 0,
646            )
647        else:
648            return self._cursor_per_partition[partition_key]
649
650    def limit_reached(self) -> bool:
651        return self._number_of_partitions > self.SWITCH_TO_GLOBAL_LIMIT
652
653    @staticmethod
654    def get_parent_state(
655        stream_state: Optional[StreamState], parent_stream_name: str
656    ) -> Optional[AirbyteStateMessage]:
657        if not stream_state:
658            return None
659
660        if "parent_state" not in stream_state:
661            logger.warning(
662                f"Trying to get_parent_state for stream `{parent_stream_name}` when there are not parent state in the state"
663            )
664            return None
665        elif parent_stream_name not in stream_state["parent_state"]:
666            logger.info(
667                f"Could not find parent state for stream `{parent_stream_name}`. On parents available are {list(stream_state['parent_state'].keys())}"
668            )
669            return None
670
671        return AirbyteStateMessage(
672            type=AirbyteStateType.STREAM,
673            stream=AirbyteStreamState(
674                stream_descriptor=StreamDescriptor(parent_stream_name, None),
675                stream_state=AirbyteStateBlob(stream_state["parent_state"][parent_stream_name]),
676            ),
677        )
678
679    @staticmethod
680    def get_global_state(
681        stream_state: Optional[StreamState], parent_stream_name: str
682    ) -> Optional[AirbyteStateMessage]:
683        return (
684            AirbyteStateMessage(
685                type=AirbyteStateType.STREAM,
686                stream=AirbyteStreamState(
687                    stream_descriptor=StreamDescriptor(parent_stream_name, None),
688                    stream_state=AirbyteStateBlob(stream_state["state"]),
689                ),
690            )
691            if stream_state and "state" in stream_state
692            else None
693        )
694
695    def get_cursor_datetime_from_state(
696        self, stream_state: Mapping[str, Any]
697    ) -> datetime.datetime | None:
698        """Extract and parse the cursor datetime from the global cursor in per-partition state.
699
700        For per-partition cursors, the global cursor is stored under the "state" key.
701        This method delegates to the underlying cursor factory to parse the datetime.
702
703        Returns None if the global cursor is not present or cannot be parsed.
704        """
705        global_state = stream_state.get(self._GLOBAL_STATE_KEY)
706        if not global_state or not isinstance(global_state, dict):
707            return None
708
709        # Create a cursor to delegate the parsing
710        cursor = self._cursor_factory.create(stream_state={}, runtime_lookback_window=None)
711        return cursor.get_cursor_datetime_from_state(global_state)
712
713    def split_request_window(
714        self, stream_slice: StreamSlice, min_split_window: Optional[timedelta] = None
715    ) -> Optional[List[StreamSlice]]:
716        """
717        Split `stream_slice` in half the way any of this stream's per-partition cursors would.
718
719        `ConcurrentCursor.split_request_window` only reads the slice's boundaries and the cursor's granularity
720        and format, never the cursor's state, and every per-partition cursor is built by the same
721        `_cursor_factory`. So one state-free cursor can split the slices of every partition, including after
722        the switch to a global cursor, when the partition's own cursor may already have been evicted. The
723        children keep `stream_slice`'s `partition` and `extra_fields`, and `SimpleRetriever` re-associates the
724        records read from them with the original slice, so `observe` and `close_partition` are unaffected.
725
726        As with an unpartitioned stream, the children are not clamped again to the cursor's start or end.
727        """
728        return self._get_request_window_splitting_cursor().split_request_window(
729            stream_slice, min_split_window
730        )
731
732    def _get_request_window_splitting_cursor(self) -> ConcurrentCursor:
733        # Built on first use so that streams that never split a window do not pay for an extra cursor.
734        with self._lock:
735            if self._request_window_splitting_cursor is None:
736                self._request_window_splitting_cursor = self._cursor_factory.create(
737                    stream_state={}, runtime_lookback_window=None
738                )
739            return self._request_window_splitting_cursor

Manages state per partition when a stream has many partitions, preventing data loss or duplication.

Attributes:
  • DEFAULT_MAX_PARTITIONS_NUMBER (int): Maximum number of partitions to retain in memory (default is 10,000). This limit needs to be higher than the number of threads we might enqueue (which is represented by ThreadPoolManager.DEFAULT_MAX_QUEUE_SIZE). If not, we could have partitions that have been generated and submitted to the ThreadPool but got deleted from the ConcurrentPerPartitionCursor and when closing them, it will generate KeyError.

    • Partition Limitation Logic Ensures the number of tracked partitions does not exceed the specified limit to prevent memory overuse. Oldest partitions are removed when the limit is reached.

    • Global Cursor Fallback New partitions use global state as the initial state to progress the state for deleted or new partitions. The history data added after the initial sync will be missing.

CurrentPerPartitionCursor expects the state of the ConcurrentCursor to follow the format {cursor_field: cursor_value}.

ConcurrentPerPartitionCursor( cursor_factory: ConcurrentCursorFactory, partition_router: airbyte_cdk.sources.declarative.partition_routers.PartitionRouter, stream_name: str, stream_namespace: Optional[str], stream_state: Any, message_repository: airbyte_cdk.MessageRepository, connector_state_manager: airbyte_cdk.ConnectorStateManager, connector_state_converter: airbyte_cdk.sources.streams.concurrent.state_converters.abstract_stream_state_converter.AbstractStreamStateConverter, cursor_field: airbyte_cdk.CursorField, use_global_cursor: bool = False, attempt_to_create_cursor_if_not_provided: bool = False)
136    def __init__(
137        self,
138        cursor_factory: ConcurrentCursorFactory,
139        partition_router: PartitionRouter,
140        stream_name: str,
141        stream_namespace: Optional[str],
142        stream_state: Any,
143        message_repository: MessageRepository,
144        connector_state_manager: ConnectorStateManager,
145        connector_state_converter: AbstractStreamStateConverter,
146        cursor_field: CursorField,
147        use_global_cursor: bool = False,
148        attempt_to_create_cursor_if_not_provided: bool = False,
149    ) -> None:
150        self._global_cursor: Optional[StreamState] = {}
151        self._stream_name = stream_name
152        self._stream_namespace = stream_namespace
153        self._message_repository = message_repository
154        self._connector_state_manager = connector_state_manager
155        self._connector_state_converter = connector_state_converter
156        self._cursor_field = cursor_field
157
158        self._cursor_factory = cursor_factory  # self._cursor_factory is flagged as private but is used in model_to_component_factory to ease pagination reset instantiation
159        self._partition_router = partition_router
160
161        # The dict is ordered to ensure that once the maximum number of partitions is reached,
162        # the oldest partitions can be efficiently removed, maintaining the most recent partitions.
163        self._cursor_per_partition: OrderedDict[str, ConcurrentCursor] = OrderedDict()
164        self._semaphore_per_partition: OrderedDict[str, threading.Semaphore] = OrderedDict()
165
166        # Parent-state tracking: store each partition’s parent state in creation order
167        self._partition_parent_state_map: OrderedDict[str, tuple[Mapping[str, Any], int]] = (
168            OrderedDict()
169        )
170        self._parent_state: Optional[StreamState] = None
171
172        # Tracks when the last slice for partition is emitted
173        self._partitions_done_generating_stream_slices: set[str] = set()
174        # Used to track the index of partitions that are not closed yet
175        self._processing_partitions_indexes: List[int] = list()
176        self._generated_partitions_count: int = 0
177        # Dictionary to map partition keys to their index
178        self._partition_key_to_index: dict[str, int] = {}
179
180        self._lock = threading.Lock()
181        self._request_window_splitting_cursor: Optional[ConcurrentCursor] = None
182        self._lookback_window: int = 0
183        self._new_global_cursor: Optional[StreamState] = None
184        self._number_of_partitions: int = 0
185        self._use_global_cursor: bool = use_global_cursor
186        self._partition_serializer = PerPartitionKeySerializer()
187
188        # Track the last time a state message was emitted
189        self._last_emission_time: float = 0.0
190        self._timer = Timer()
191
192        self._set_initial_state(stream_state)
193
194        # FIXME this is a temporary field the time of the migration from declarative cursors to concurrent ones
195        self._attempt_to_create_cursor_if_not_provided = attempt_to_create_cursor_if_not_provided
196        self._synced_some_data = False
197        self._finished_generating_slices = False
198        self._logged_regarding_datetime_format_error = False
DEFAULT_MAX_PARTITIONS_NUMBER = 25000
SWITCH_TO_GLOBAL_LIMIT = 10000
STATE_EMIT_INTERVAL_SECONDS: float = 600
cursor_field: airbyte_cdk.CursorField
200    @property
201    def cursor_field(self) -> CursorField:
202        return self._cursor_field
204    @property
205    def partition_router(self) -> PartitionRouter:
206        return self._partition_router
state: MutableMapping[str, Any]
208    @property
209    def state(self) -> MutableMapping[str, Any]:
210        state: dict[str, Any] = {"use_global_cursor": self._use_global_cursor}
211        if not self._use_global_cursor:
212            states = []
213            for partition_tuple, cursor in self._cursor_per_partition.items():
214                if cursor.state:
215                    states.append(
216                        {
217                            "partition": self._to_dict(partition_tuple),
218                            "cursor": copy.deepcopy(cursor.state),
219                        }
220                    )
221            state[self._PERPARTITION_STATE_KEY] = states
222
223        if self._global_cursor:
224            state[self._GLOBAL_STATE_KEY] = self._global_cursor
225        if self._lookback_window is not None:
226            state["lookback_window"] = self._lookback_window
227        if self._parent_state is not None:
228            state["parent_state"] = self._parent_state
229        return state
def close_partition( self, partition: airbyte_cdk.sources.streams.concurrent.partitions.partition.Partition) -> None:
231    def close_partition(self, partition: Partition) -> None:
232        # Attempt to retrieve the stream slice
233        stream_slice: Optional[StreamSlice] = partition.to_slice()  # type: ignore[assignment]
234
235        # Ensure stream_slice is not None
236        if stream_slice is None:
237            raise ValueError("stream_slice cannot be None")
238
239        partition_key = self._to_partition_key(stream_slice.partition)
240        with self._lock:
241            self._semaphore_per_partition[partition_key].acquire()
242            if not self._use_global_cursor:
243                cursor = self._cursor_per_partition[partition_key]
244                cursor.close_partition(partition=partition)
245                if (
246                    partition_key in self._partitions_done_generating_stream_slices
247                    and self._semaphore_per_partition[partition_key]._value == 0
248                ):
249                    self._update_global_cursor(cursor.state[self.cursor_field.cursor_field_key])
250
251            # Clean up the partition if it is fully processed
252            self._cleanup_if_done(partition_key)
253
254            self._check_and_update_parent_state()
255
256            self._emit_state_message()

Indicate to the cursor that the partition has been successfully processed

def ensure_at_least_one_state_emitted(self) -> None:
280    def ensure_at_least_one_state_emitted(self) -> None:
281        """
282        The platform expects at least one state message on successful syncs. Hence, whatever happens, we expect this method to be
283        called.
284
285        If the stream did not complete (a partition was never closed, or slice generation stopped early), the global cursor is not
286        advanced, because partitions that were never generated have not been read up to it. If the state then holds no
287        checkpoint, nothing is emitted. Such a state records no progress, but it is not empty, so the next attempt would treat
288        the stream as already synced once: a StateDelegatingStream would switch to its incremental stream and never read the
289        slices this attempt missed. This covers global-cursor streams; in per-partition mode the cursor of every generated
290        partition reports its start value, so the state is still emitted.
291
292        If slice generation stopped early, the parent state is not refreshed from the partition router: the router may already have closed a parent slice whose last child slice was never generated, so only the parent state recorded by `_check_and_update_parent_state` for closed child partitions is kept.
293        """
294        all_partitions_closed = not any(
295            semaphore_item[1]._value for semaphore_item in self._semaphore_per_partition.items()
296        )
297        stream_completed = all_partitions_closed and self._finished_generating_slices
298        if all_partitions_closed:
299            if self._synced_some_data and stream_completed:
300                # we only update those if we actually synced some data
301                self._global_cursor = self._new_global_cursor
302                self._lookback_window = self._timer.finish()
303            if stream_completed:
304                self._parent_state = self._partition_router.get_stream_state()
305        if not stream_completed and not self._has_checkpoint():
306            return
307        self._emit_state_message(throttle=False)

The platform expects at least one state message on successful syncs. Hence, whatever happens, we expect this method to be called.

If the stream did not complete (a partition was never closed, or slice generation stopped early), the global cursor is not advanced, because partitions that were never generated have not been read up to it. If the state then holds no checkpoint, nothing is emitted. Such a state records no progress, but it is not empty, so the next attempt would treat the stream as already synced once: a StateDelegatingStream would switch to its incremental stream and never read the slices this attempt missed. This covers global-cursor streams; in per-partition mode the cursor of every generated partition reports its start value, so the state is still emitted.

If slice generation stopped early, the parent state is not refreshed from the partition router: the router may already have closed a parent slice whose last child slice was never generated, so only the parent state recorded by _check_and_update_parent_state for closed child partitions is kept.

def stream_slices(self) -> Iterable[airbyte_cdk.StreamSlice]:
346    def stream_slices(self) -> Iterable[StreamSlice]:
347        if self._timer.is_running():
348            raise RuntimeError("stream_slices has been executed more than once.")
349
350        slices = self._partition_router.stream_slices()
351        self._timer.start()
352        for partition, last, parent_state in iterate_with_last_flag_and_state(
353            slices, self._partition_router.get_stream_state
354        ):
355            yield from self._generate_slices_from_partition(partition, parent_state)
356        self._finished_generating_slices = True

Default placeholder implementation of generate_slices. Subclasses can override this method to provide actual behavior.

def observe(self, record: airbyte_cdk.Record) -> None:
543    def observe(self, record: Record) -> None:
544        if not record.associated_slice:
545            raise ValueError(
546                "Invalid state as stream slices that are emitted should refer to an existing cursor"
547            )
548
549        # if the current record has no cursor value, we cannot meaningfully update the state based on it, so there is nothing more to do
550        try:
551            record_cursor_value = self._cursor_field.extract_value(record)
552        except ValueError:
553            return
554
555        try:
556            record_cursor = self._connector_state_converter.output_format(
557                self._connector_state_converter.parse_value(record_cursor_value)
558            )
559        except ValueError as exception:
560            if not self._logged_regarding_datetime_format_error:
561                logger.warning(
562                    "Skipping cursor update for stream '%s': failed to parse cursor field '%s' value %r: %s",
563                    self._stream_name,
564                    self._cursor_field.cursor_field_key,
565                    record_cursor_value,
566                    exception,
567                )
568                self._logged_regarding_datetime_format_error = True
569            return
570
571        self._synced_some_data = True
572        self._update_global_cursor(record_cursor)
573        if not self._use_global_cursor:
574            self._cursor_per_partition[
575                self._to_partition_key(record.associated_slice.partition)
576            ].observe(record)

Indicate to the cursor that the record has been emitted

def should_be_synced(self, record: airbyte_cdk.Record) -> bool:
619    def should_be_synced(self, record: Record) -> bool:
620        return self._get_cursor(record).should_be_synced(record)
def limit_reached(self) -> bool:
650    def limit_reached(self) -> bool:
651        return self._number_of_partitions > self.SWITCH_TO_GLOBAL_LIMIT
@staticmethod
def get_parent_state( stream_state: Optional[Mapping[str, Any]], parent_stream_name: str) -> Optional[airbyte_cdk.models.airbyte_protocol.AirbyteStateMessage]:
653    @staticmethod
654    def get_parent_state(
655        stream_state: Optional[StreamState], parent_stream_name: str
656    ) -> Optional[AirbyteStateMessage]:
657        if not stream_state:
658            return None
659
660        if "parent_state" not in stream_state:
661            logger.warning(
662                f"Trying to get_parent_state for stream `{parent_stream_name}` when there are not parent state in the state"
663            )
664            return None
665        elif parent_stream_name not in stream_state["parent_state"]:
666            logger.info(
667                f"Could not find parent state for stream `{parent_stream_name}`. On parents available are {list(stream_state['parent_state'].keys())}"
668            )
669            return None
670
671        return AirbyteStateMessage(
672            type=AirbyteStateType.STREAM,
673            stream=AirbyteStreamState(
674                stream_descriptor=StreamDescriptor(parent_stream_name, None),
675                stream_state=AirbyteStateBlob(stream_state["parent_state"][parent_stream_name]),
676            ),
677        )
@staticmethod
def get_global_state( stream_state: Optional[Mapping[str, Any]], parent_stream_name: str) -> Optional[airbyte_cdk.models.airbyte_protocol.AirbyteStateMessage]:
679    @staticmethod
680    def get_global_state(
681        stream_state: Optional[StreamState], parent_stream_name: str
682    ) -> Optional[AirbyteStateMessage]:
683        return (
684            AirbyteStateMessage(
685                type=AirbyteStateType.STREAM,
686                stream=AirbyteStreamState(
687                    stream_descriptor=StreamDescriptor(parent_stream_name, None),
688                    stream_state=AirbyteStateBlob(stream_state["state"]),
689                ),
690            )
691            if stream_state and "state" in stream_state
692            else None
693        )
def get_cursor_datetime_from_state(self, stream_state: Mapping[str, Any]) -> datetime.datetime | None:
695    def get_cursor_datetime_from_state(
696        self, stream_state: Mapping[str, Any]
697    ) -> datetime.datetime | None:
698        """Extract and parse the cursor datetime from the global cursor in per-partition state.
699
700        For per-partition cursors, the global cursor is stored under the "state" key.
701        This method delegates to the underlying cursor factory to parse the datetime.
702
703        Returns None if the global cursor is not present or cannot be parsed.
704        """
705        global_state = stream_state.get(self._GLOBAL_STATE_KEY)
706        if not global_state or not isinstance(global_state, dict):
707            return None
708
709        # Create a cursor to delegate the parsing
710        cursor = self._cursor_factory.create(stream_state={}, runtime_lookback_window=None)
711        return cursor.get_cursor_datetime_from_state(global_state)

Extract and parse the cursor datetime from the global cursor in per-partition state.

For per-partition cursors, the global cursor is stored under the "state" key. This method delegates to the underlying cursor factory to parse the datetime.

Returns None if the global cursor is not present or cannot be parsed.

def split_request_window( self, stream_slice: airbyte_cdk.StreamSlice, min_split_window: Optional[datetime.timedelta] = None) -> Optional[List[airbyte_cdk.StreamSlice]]:
713    def split_request_window(
714        self, stream_slice: StreamSlice, min_split_window: Optional[timedelta] = None
715    ) -> Optional[List[StreamSlice]]:
716        """
717        Split `stream_slice` in half the way any of this stream's per-partition cursors would.
718
719        `ConcurrentCursor.split_request_window` only reads the slice's boundaries and the cursor's granularity
720        and format, never the cursor's state, and every per-partition cursor is built by the same
721        `_cursor_factory`. So one state-free cursor can split the slices of every partition, including after
722        the switch to a global cursor, when the partition's own cursor may already have been evicted. The
723        children keep `stream_slice`'s `partition` and `extra_fields`, and `SimpleRetriever` re-associates the
724        records read from them with the original slice, so `observe` and `close_partition` are unaffected.
725
726        As with an unpartitioned stream, the children are not clamped again to the cursor's start or end.
727        """
728        return self._get_request_window_splitting_cursor().split_request_window(
729            stream_slice, min_split_window
730        )

Split stream_slice in half the way any of this stream's per-partition cursors would.

ConcurrentCursor.split_request_window only reads the slice's boundaries and the cursor's granularity and format, never the cursor's state, and every per-partition cursor is built by the same _cursor_factory. So one state-free cursor can split the slices of every partition, including after the switch to a global cursor, when the partition's own cursor may already have been evicted. The children keep stream_slice's partition and extra_fields, and SimpleRetriever re-associates the records read from them with the original slice, so observe and close_partition are unaffected.

As with an unpartitioned stream, the children are not clamped again to the cursor's start or end.

class SyncTokenCursor(airbyte_cdk.sources.streams.concurrent.cursor.Cursor):
 44class SyncTokenCursor(Cursor):
 45    """Track opaque API-issued sync tokens and commit them after a complete partition read.
 46
 47    Unpartitioned state is ``{"state_type": "sync_token", "token": "..."}``; partitioned
 48    state stores a ``states`` list pairing each partition with its token. Tokens become committed
 49    state only in ``close_partition``. Partitioned state is capped at 25,000 entries.
 50    """
 51
 52    STATE_TYPE = "sync_token"
 53
 54    def __init__(
 55        self,
 56        *,
 57        stream_name: str,
 58        stream_namespace: Optional[str],
 59        stream_state: Optional[StreamState],
 60        message_repository: MessageRepository,
 61        connector_state_manager: ConnectorStateManager,
 62        partition_router: PartitionRouter,
 63        token_path: list[str],
 64        decoder: Decoder,
 65        config: Config,
 66        parameters: Mapping[str, Any],
 67        completion_condition: Optional[str] = None,
 68        cursor_field: Optional[str] = None,
 69        max_partitions: int = ConcurrentPerPartitionCursor.DEFAULT_MAX_PARTITIONS_NUMBER,
 70    ) -> None:
 71        self._stream_name = stream_name
 72        self._stream_namespace = stream_namespace
 73        self._message_repository = message_repository
 74        self._connector_state_manager = connector_state_manager
 75        self._partition_router = partition_router
 76        self._partitioned = not isinstance(partition_router, SinglePartitionRouter)
 77        self._token_path = [
 78            InterpolatedString.create(path, parameters=parameters) for path in token_path
 79        ]
 80        self._decoder = decoder
 81        self._config = config
 82        self._completion_condition = (
 83            InterpolatedBoolean(completion_condition, parameters=parameters)
 84            if completion_condition is not None
 85            else None
 86        )
 87        self.cursor_field = CursorField(cursor_field) if cursor_field else None
 88        self._max_partitions = max_partitions
 89        self._serializer = PerPartitionKeySerializer()
 90        self._committed: OrderedDict[str, dict[str, Any]] = OrderedDict()
 91        self._pending: dict[str, dict[str, Any]] = {}
 92        self._page_counts: dict[str, int] = {}
 93        self._lock = threading.RLock()
 94        self._last_emission_time = 0.0
 95        self._logged_bootstrap_reasons: set[str] = set()
 96        self._state_is_foreign = False
 97        self._state_emitted = False
 98        self._warned_no_token = False
 99        self._warned_cap = False
100        self._partitions_over_cap: set[str] = set()
101        self._invalid_state_reason: Optional[str] = None
102        self._load_state(stream_state or {})
103
104    @property
105    def decoder(self) -> Decoder:
106        return self._decoder
107
108    @property
109    def partitioned(self) -> bool:
110        return self._partitioned
111
112    @property
113    def partition_router(self) -> PartitionRouter:
114        return self._partition_router
115
116    @property
117    def state(self) -> MutableMapping[str, Any]:
118        with self._lock:
119            if not self._partitioned:
120                state: dict[str, Any] = {"state_type": self.STATE_TYPE}
121                if self._committed:
122                    state.update(copy.deepcopy(next(iter(self._committed.values()))))
123                return state
124            return {
125                "state_type": self.STATE_TYPE,
126                "states": [
127                    {
128                        "partition": self._serializer.to_partition(partition_key),
129                        "cursor": copy.deepcopy(cursor),
130                    }
131                    for partition_key, cursor in self._committed.items()
132                ],
133            }
134
135    def stream_slices(self) -> Iterable[StreamSlice]:
136        if self._invalid_state_reason is not None:
137            message = (
138                f"Stream {self._stream_name}: the saved sync token state is malformed "
139                f"({self._invalid_state_reason}). Refresh the stream to start a new full sync."
140            )
141            raise AirbyteTracedException(
142                message=message, internal_message=message, failure_type=FailureType.system_error
143            )
144        seen_partitions: set[str] = set()
145        for stream_slice in self._partition_router.stream_slices():
146            partition = dict(stream_slice.partition or {})
147            if "token" in partition:
148                message = f"Stream {self._stream_name}: partition router uses reserved key 'token'"
149                raise AirbyteTracedException(
150                    message=message,
151                    internal_message=message,
152                    failure_type=FailureType.config_error,
153                )
154            partition_key = self._serializer.to_partition_key(partition)
155            if partition_key in seen_partitions:
156                continue
157            seen_partitions.add(partition_key)
158            with self._lock:
159                committed = self._committed.get(partition_key)
160                token = committed["token"] if committed else None
161                at_partition_cap = len(self._committed) >= self._max_partitions
162                if token:
163                    self._log_replay(partition, committed or {})
164                elif at_partition_cap:
165                    self._partitions_over_cap.add(partition_key)
166                    self._log_bootstrap("partition cap")
167                elif not self._state_is_foreign:
168                    self._log_bootstrap("none")
169            yield StreamSlice(
170                partition=partition,
171                cursor_slice={"token": token} if token else {},
172                extra_fields=stream_slice.extra_fields,
173            )
174
175        if self._partitioned:
176            with self._lock:
177                vanished = set(self._committed) - seen_partitions
178                for partition_key in vanished:
179                    del self._committed[partition_key]
180                if vanished:
181                    logger.info(
182                        "Stream %s: dropped the stored tokens of %s partitions the router no longer returns.",
183                        self._stream_name,
184                        len(vanished),
185                    )
186
187    def on_page_completed(self, page: PageCompleted) -> None:
188        partition_key = self._serializer.to_partition_key(page.stream_slice.partition or {})
189        with self._lock:
190            self._page_counts[partition_key] = self._page_counts.get(partition_key, 0) + 1
191
192        if not page.pagination_exhausted or page.response is None:
193            return
194
195        body = next(
196            (
197                decoded
198                for decoded in self._decoder.decode(page.response)
199                if isinstance(decoded, Mapping)
200            ),
201            {},
202        )
203        path = [str(part.eval(self._config)) for part in self._token_path]
204        token_value = dpath.get(body, path, default=None) if isinstance(body, Mapping) else None
205        if self._completion_condition is not None:
206            complete = self._completion_condition.eval(
207                self._config,
208                response=body,
209                headers=page.response.headers,
210                stream_slice=page.stream_slice,
211            )
212        else:
213            complete = True
214        if not complete:
215            self._warn_missing_token()
216            return
217
218        token = self._coerce_token(token_value, path)
219        if token is None:
220            self._warn_missing_token()
221            return
222
223        with self._lock:
224            self._pending[partition_key] = {
225                "token": token,
226                "committed_at": datetime.datetime.now(datetime.timezone.utc)
227                .isoformat(timespec="milliseconds")
228                .replace("+00:00", "Z"),
229            }
230
231    def _coerce_token(self, value: Any, path: list[str]) -> Optional[str]:
232        if value is None or value == "":
233            return None
234        if isinstance(value, bool):
235            value_type = "boolean"
236        elif isinstance(value, str):
237            return value
238        elif isinstance(value, int):
239            return str(value)
240        elif isinstance(value, float):
241            value_type = "float"
242        elif isinstance(value, Mapping):
243            value_type = "dict"
244        elif isinstance(value, list):
245            value_type = "list"
246        else:
247            value_type = type(value).__name__
248        message = (
249            f"Stream {self._stream_name}: token_path {json.dumps(path)} holds a {value_type}, "
250            "not a string or integer. Check token_path."
251        )
252        raise AirbyteTracedException(
253            internal_message=message,
254            message=message,
255            failure_type=FailureType.system_error,
256        )
257
258    def _log_bootstrap(self, reason: str) -> None:
259        if reason not in self._logged_bootstrap_reasons:
260            logger.info(
261                "Stream %s: no stored sync token (reason: %s); reading all records.",
262                self._stream_name,
263                reason,
264            )
265            self._logged_bootstrap_reasons.add(reason)
266
267    def _log_foreign_state(self) -> None:
268        self._state_is_foreign = True
269        logger.warning(
270            "Stream %s: the saved state belongs to another cursor type; reading all records once.",
271            self._stream_name,
272        )
273
274    def _log_replay(self, partition: Mapping[str, Any], committed: Mapping[str, Any]) -> None:
275        age = self._human_age(committed.get("committed_at"))
276        if self._partitioned:
277            logger.debug(
278                "Stream %s: replaying the sync token committed %s ago for partition %s.",
279                self._stream_name,
280                age,
281                dict(partition),
282            )
283        else:
284            logger.info(
285                "Stream %s: replaying the sync token committed %s ago.",
286                self._stream_name,
287                age,
288            )
289
290    @staticmethod
291    def _human_age(committed_at: Any) -> str:
292        if not isinstance(committed_at, str) or not committed_at:
293            return "an unknown time"
294        try:
295            committed_time = datetime.datetime.fromisoformat(committed_at.replace("Z", "+00:00"))
296            if committed_time.tzinfo is None:
297                committed_time = committed_time.replace(tzinfo=datetime.timezone.utc)
298            age_seconds = max(
299                0,
300                int(
301                    (datetime.datetime.now(datetime.timezone.utc) - committed_time).total_seconds()
302                ),
303            )
304        except (OverflowError, ValueError):
305            return "an unknown time"
306
307        units = (
308            ("day", 24 * 60 * 60),
309            ("hour", 60 * 60),
310            ("minute", 60),
311            ("second", 1),
312        )
313        parts = []
314        for unit, unit_seconds in units:
315            count, age_seconds = divmod(age_seconds, unit_seconds)
316            if count:
317                parts.append(f"{count} {unit}{'' if count == 1 else 's'}")
318            if len(parts) == 2:
319                break
320        return " ".join(parts) if parts else "0 seconds"
321
322    def _warn_missing_token(self) -> None:
323        if not self._warned_no_token:
324            logger.warning(
325                "Stream %s: pagination ended without a new sync token; kept the stored token. "
326                "The next sync re-reads from it.",
327                self._stream_name,
328            )
329            self._warned_no_token = True
330
331    def close_partition(self, partition: Partition) -> None:
332        stream_slice = partition.to_slice()
333        if stream_slice is None:
334            raise ValueError("stream_slice cannot be None")
335        partition_values = getattr(stream_slice, "partition", None)
336        if partition_values is None:
337            partition_values = stream_slice.get("partition", {})
338        partition_key = self._serializer.to_partition_key(partition_values)
339        with self._lock:
340            pending = self._pending.pop(partition_key, None)
341            page_count = self._page_counts.pop(partition_key, 0)
342            if pending is not None:
343                if partition_key in self._committed or len(self._committed) < self._max_partitions:
344                    self._committed[partition_key] = pending
345                    self._partitions_over_cap.discard(partition_key)
346                    logger.debug(
347                        "Stream %s: committed sync token %s for partition %s after %s pages.",
348                        self._stream_name,
349                        pending["token"],
350                        self._serializer.to_partition(partition_key),
351                        page_count,
352                    )
353                else:
354                    self._partitions_over_cap.add(partition_key)
355            if not self._partitioned:
356                self._emit_state_message()
357            elif time.time() - self._last_emission_time > 600:
358                self._emit_state_message()
359
360    def _emit_state_message(self) -> None:
361        self._last_emission_time = time.time()
362        self._connector_state_manager.update_state_for_stream(
363            self._stream_name, self._stream_namespace, self.state
364        )
365        self._message_repository.emit_message(
366            self._connector_state_manager.create_state_message(
367                self._stream_name, self._stream_namespace
368            )
369        )
370        self._state_emitted = True
371
372    def ensure_at_least_one_state_emitted(self) -> None:
373        if self._invalid_state_reason is not None:
374            return  # leave the malformed state in place for diagnosis
375        if self._partitioned or not self._state_emitted:
376            self._emit_state_message()
377        if self._partitions_over_cap and not self._warned_cap:
378            logger.warning(
379                "Stream %s: %s partitions already store tokens; %s more read in full on every sync.",
380                self._stream_name,
381                len(self._committed),
382                len(self._partitions_over_cap),
383            )
384            self._warned_cap = True
385
386    def observe(self, record: Record) -> None:
387        return
388
389    def should_be_synced(self, record: Record) -> bool:
390        return True
391
392    def _load_state(self, stream_state: StreamState) -> None:
393        if not stream_state:
394            self._log_bootstrap("none")
395            return
396        if stream_state.get("state_type") != self.STATE_TYPE:
397            self._log_foreign_state()
398            return
399        if self._partitioned:
400            states = stream_state.get("states")
401            if not isinstance(states, list) or "token" in stream_state:
402                if "token" not in stream_state and "states" not in stream_state:
403                    self._log_bootstrap("none")
404                else:
405                    self._invalid_state_reason = "unpartitioned shape on a partitioned stream"
406                return
407            committed: dict[str, dict[str, Any]] = {}
408            for state in states:
409                if not isinstance(state, Mapping):
410                    self._invalid_state_reason = "a partition entry is not an object"
411                    return
412                partition = state.get("partition")
413                cursor = state.get("cursor")
414                if (
415                    isinstance(partition, Mapping)
416                    and isinstance(cursor, Mapping)
417                    and isinstance(cursor.get("token"), str)
418                    and cursor.get("token")
419                ):
420                    committed[self._serializer.to_partition_key(partition)] = {
421                        "token": cursor["token"],
422                        "committed_at": cursor.get("committed_at", ""),
423                    }
424                else:
425                    self._invalid_state_reason = "a partition entry has no valid token"
426                    return
427            self._committed.update(committed)
428        else:
429            if "states" in stream_state:
430                self._invalid_state_reason = "partitioned shape on an unpartitioned stream"
431                return
432            token = stream_state.get("token")
433            if isinstance(token, str) and token:
434                self._committed["{}"] = {
435                    "token": token,
436                    "committed_at": stream_state.get("committed_at", ""),
437                }
438            elif "token" in stream_state:
439                self._invalid_state_reason = "the token is not a non-empty string"

Track opaque API-issued sync tokens and commit them after a complete partition read.

Unpartitioned state is {"state_type": "sync_token", "token": "..."}; partitioned state stores a states list pairing each partition with its token. Tokens become committed state only in close_partition. Partitioned state is capped at 25,000 entries.

SyncTokenCursor( *, stream_name: str, stream_namespace: Optional[str], stream_state: Optional[Mapping[str, Any]], message_repository: airbyte_cdk.MessageRepository, connector_state_manager: airbyte_cdk.ConnectorStateManager, partition_router: airbyte_cdk.sources.declarative.partition_routers.PartitionRouter, token_path: list[str], decoder: airbyte_cdk.Decoder, config: Mapping[str, Any], parameters: Mapping[str, Any], completion_condition: Optional[str] = None, cursor_field: Optional[str] = None, max_partitions: int = 25000)
 54    def __init__(
 55        self,
 56        *,
 57        stream_name: str,
 58        stream_namespace: Optional[str],
 59        stream_state: Optional[StreamState],
 60        message_repository: MessageRepository,
 61        connector_state_manager: ConnectorStateManager,
 62        partition_router: PartitionRouter,
 63        token_path: list[str],
 64        decoder: Decoder,
 65        config: Config,
 66        parameters: Mapping[str, Any],
 67        completion_condition: Optional[str] = None,
 68        cursor_field: Optional[str] = None,
 69        max_partitions: int = ConcurrentPerPartitionCursor.DEFAULT_MAX_PARTITIONS_NUMBER,
 70    ) -> None:
 71        self._stream_name = stream_name
 72        self._stream_namespace = stream_namespace
 73        self._message_repository = message_repository
 74        self._connector_state_manager = connector_state_manager
 75        self._partition_router = partition_router
 76        self._partitioned = not isinstance(partition_router, SinglePartitionRouter)
 77        self._token_path = [
 78            InterpolatedString.create(path, parameters=parameters) for path in token_path
 79        ]
 80        self._decoder = decoder
 81        self._config = config
 82        self._completion_condition = (
 83            InterpolatedBoolean(completion_condition, parameters=parameters)
 84            if completion_condition is not None
 85            else None
 86        )
 87        self.cursor_field = CursorField(cursor_field) if cursor_field else None
 88        self._max_partitions = max_partitions
 89        self._serializer = PerPartitionKeySerializer()
 90        self._committed: OrderedDict[str, dict[str, Any]] = OrderedDict()
 91        self._pending: dict[str, dict[str, Any]] = {}
 92        self._page_counts: dict[str, int] = {}
 93        self._lock = threading.RLock()
 94        self._last_emission_time = 0.0
 95        self._logged_bootstrap_reasons: set[str] = set()
 96        self._state_is_foreign = False
 97        self._state_emitted = False
 98        self._warned_no_token = False
 99        self._warned_cap = False
100        self._partitions_over_cap: set[str] = set()
101        self._invalid_state_reason: Optional[str] = None
102        self._load_state(stream_state or {})
STATE_TYPE = 'sync_token'
cursor_field
decoder: airbyte_cdk.Decoder
104    @property
105    def decoder(self) -> Decoder:
106        return self._decoder
partitioned: bool
108    @property
109    def partitioned(self) -> bool:
110        return self._partitioned
112    @property
113    def partition_router(self) -> PartitionRouter:
114        return self._partition_router
state: MutableMapping[str, Any]
116    @property
117    def state(self) -> MutableMapping[str, Any]:
118        with self._lock:
119            if not self._partitioned:
120                state: dict[str, Any] = {"state_type": self.STATE_TYPE}
121                if self._committed:
122                    state.update(copy.deepcopy(next(iter(self._committed.values()))))
123                return state
124            return {
125                "state_type": self.STATE_TYPE,
126                "states": [
127                    {
128                        "partition": self._serializer.to_partition(partition_key),
129                        "cursor": copy.deepcopy(cursor),
130                    }
131                    for partition_key, cursor in self._committed.items()
132                ],
133            }
def stream_slices(self) -> Iterable[airbyte_cdk.StreamSlice]:
135    def stream_slices(self) -> Iterable[StreamSlice]:
136        if self._invalid_state_reason is not None:
137            message = (
138                f"Stream {self._stream_name}: the saved sync token state is malformed "
139                f"({self._invalid_state_reason}). Refresh the stream to start a new full sync."
140            )
141            raise AirbyteTracedException(
142                message=message, internal_message=message, failure_type=FailureType.system_error
143            )
144        seen_partitions: set[str] = set()
145        for stream_slice in self._partition_router.stream_slices():
146            partition = dict(stream_slice.partition or {})
147            if "token" in partition:
148                message = f"Stream {self._stream_name}: partition router uses reserved key 'token'"
149                raise AirbyteTracedException(
150                    message=message,
151                    internal_message=message,
152                    failure_type=FailureType.config_error,
153                )
154            partition_key = self._serializer.to_partition_key(partition)
155            if partition_key in seen_partitions:
156                continue
157            seen_partitions.add(partition_key)
158            with self._lock:
159                committed = self._committed.get(partition_key)
160                token = committed["token"] if committed else None
161                at_partition_cap = len(self._committed) >= self._max_partitions
162                if token:
163                    self._log_replay(partition, committed or {})
164                elif at_partition_cap:
165                    self._partitions_over_cap.add(partition_key)
166                    self._log_bootstrap("partition cap")
167                elif not self._state_is_foreign:
168                    self._log_bootstrap("none")
169            yield StreamSlice(
170                partition=partition,
171                cursor_slice={"token": token} if token else {},
172                extra_fields=stream_slice.extra_fields,
173            )
174
175        if self._partitioned:
176            with self._lock:
177                vanished = set(self._committed) - seen_partitions
178                for partition_key in vanished:
179                    del self._committed[partition_key]
180                if vanished:
181                    logger.info(
182                        "Stream %s: dropped the stored tokens of %s partitions the router no longer returns.",
183                        self._stream_name,
184                        len(vanished),
185                    )

Default placeholder implementation of generate_slices. Subclasses can override this method to provide actual behavior.

def on_page_completed( self, page: airbyte_cdk.sources.declarative.retrievers.simple_retriever.PageCompleted) -> None:
187    def on_page_completed(self, page: PageCompleted) -> None:
188        partition_key = self._serializer.to_partition_key(page.stream_slice.partition or {})
189        with self._lock:
190            self._page_counts[partition_key] = self._page_counts.get(partition_key, 0) + 1
191
192        if not page.pagination_exhausted or page.response is None:
193            return
194
195        body = next(
196            (
197                decoded
198                for decoded in self._decoder.decode(page.response)
199                if isinstance(decoded, Mapping)
200            ),
201            {},
202        )
203        path = [str(part.eval(self._config)) for part in self._token_path]
204        token_value = dpath.get(body, path, default=None) if isinstance(body, Mapping) else None
205        if self._completion_condition is not None:
206            complete = self._completion_condition.eval(
207                self._config,
208                response=body,
209                headers=page.response.headers,
210                stream_slice=page.stream_slice,
211            )
212        else:
213            complete = True
214        if not complete:
215            self._warn_missing_token()
216            return
217
218        token = self._coerce_token(token_value, path)
219        if token is None:
220            self._warn_missing_token()
221            return
222
223        with self._lock:
224            self._pending[partition_key] = {
225                "token": token,
226                "committed_at": datetime.datetime.now(datetime.timezone.utc)
227                .isoformat(timespec="milliseconds")
228                .replace("+00:00", "Z"),
229            }
def close_partition( self, partition: airbyte_cdk.sources.streams.concurrent.partitions.partition.Partition) -> None:
331    def close_partition(self, partition: Partition) -> None:
332        stream_slice = partition.to_slice()
333        if stream_slice is None:
334            raise ValueError("stream_slice cannot be None")
335        partition_values = getattr(stream_slice, "partition", None)
336        if partition_values is None:
337            partition_values = stream_slice.get("partition", {})
338        partition_key = self._serializer.to_partition_key(partition_values)
339        with self._lock:
340            pending = self._pending.pop(partition_key, None)
341            page_count = self._page_counts.pop(partition_key, 0)
342            if pending is not None:
343                if partition_key in self._committed or len(self._committed) < self._max_partitions:
344                    self._committed[partition_key] = pending
345                    self._partitions_over_cap.discard(partition_key)
346                    logger.debug(
347                        "Stream %s: committed sync token %s for partition %s after %s pages.",
348                        self._stream_name,
349                        pending["token"],
350                        self._serializer.to_partition(partition_key),
351                        page_count,
352                    )
353                else:
354                    self._partitions_over_cap.add(partition_key)
355            if not self._partitioned:
356                self._emit_state_message()
357            elif time.time() - self._last_emission_time > 600:
358                self._emit_state_message()

Indicate to the cursor that the partition has been successfully processed

def ensure_at_least_one_state_emitted(self) -> None:
372    def ensure_at_least_one_state_emitted(self) -> None:
373        if self._invalid_state_reason is not None:
374            return  # leave the malformed state in place for diagnosis
375        if self._partitioned or not self._state_emitted:
376            self._emit_state_message()
377        if self._partitions_over_cap and not self._warned_cap:
378            logger.warning(
379                "Stream %s: %s partitions already store tokens; %s more read in full on every sync.",
380                self._stream_name,
381                len(self._committed),
382                len(self._partitions_over_cap),
383            )
384            self._warned_cap = True

State messages are emitted when a partition is closed. However, the platform expects at least one state to be emitted per sync per stream. Hence, if no partitions are generated, this method needs to be called.

def observe(self, record: airbyte_cdk.Record) -> None:
386    def observe(self, record: Record) -> None:
387        return

Indicate to the cursor that the record has been emitted

def should_be_synced(self, record: airbyte_cdk.Record) -> bool:
389    def should_be_synced(self, record: Record) -> bool:
390        return True