Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(low-code CDK): fix checkpointing for declarative streams #177

Merged
merged 3 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions airbyte_cdk/sources/streams/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,17 +223,17 @@ def read( # type: ignore # ignoring typing for ConnectorStateManager because o
record_counter += 1

checkpoint_interval = self.state_checkpoint_interval
checkpoint = checkpoint_reader.get_checkpoint()
if (
should_checkpoint
and checkpoint_interval
and record_counter % checkpoint_interval == 0
and checkpoint is not None
):
airbyte_state_message = self._checkpoint_state(
checkpoint, state_manager=state_manager
)
yield airbyte_state_message
checkpoint = checkpoint_reader.get_checkpoint()
if checkpoint:
lazebnyi marked this conversation as resolved.
Show resolved Hide resolved
airbyte_state_message = self._checkpoint_state(
checkpoint, state_manager=state_manager
)
yield airbyte_state_message

if internal_config.is_limit_reached(record_counter):
break
Expand Down
142 changes: 142 additions & 0 deletions unit_tests/sources/declarative/test_manifest_declarative_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -1901,3 +1901,145 @@ def validate_refs(yaml_file: str) -> List[str]:
/ "airbyte_cdk/sources/declarative/declarative_component_schema.yaml"
)
assert not validate_refs(yaml_file_path)


@pytest.mark.parametrize(
"test_name, manifest, pages, expected_states_qty",
[
(
"test_with_pagination_and_partition_router",
{
"version": "0.34.2",
"type": "DeclarativeSource",
"check": {"type": "CheckStream", "stream_names": ["Rates"]},
"streams": [
{
"type": "DeclarativeStream",
"name": "Rates",
"primary_key": [],
"schema_loader": {
"type": "InlineSchemaLoader",
"schema": {
"$schema": "http://json-schema.org/schema#",
"properties": {
"ABC": {"type": "number"},
"AED": {"type": "number"},
"partition": {"type": "number"},
},
"type": "object",
},
},
"retriever": {
"type": "SimpleRetriever",
"requester": {
"type": "HttpRequester",
"url_base": "https://api.apilayer.com",
"path": "/exchangerates_data/latest",
"http_method": "GET",
"request_parameters": {},
"request_headers": {},
"request_body_json": {},
"authenticator": {
"type": "ApiKeyAuthenticator",
"header": "apikey",
"api_token": "{{ config['api_key'] }}",
},
},
"partition_router": {
"type": "ListPartitionRouter",
"values": ["0", "1"],
"cursor_field": "partition",
},
"record_selector": {
"type": "RecordSelector",
"extractor": {"type": "DpathExtractor", "field_path": ["rates"]},
},
"paginator": {
"type": "DefaultPaginator",
"page_size": 2,
"page_size_option": {
"inject_into": "request_parameter",
"field_name": "page_size",
},
"page_token_option": {"inject_into": "path", "type": "RequestPath"},
"pagination_strategy": {
"type": "CursorPagination",
"cursor_value": "{{ response._metadata.next }}",
"page_size": 2,
},
},
},
"incremental_sync": {
"type": "DatetimeBasedCursor",
"cursor_datetime_formats": ["%Y-%m-%dT%H:%M:%S.%fZ"],
"datetime_format": "%Y-%m-%dT%H:%M:%S.%fZ",
"cursor_field": "updated_at",
"start_datetime": {
"datetime": "{{ config.get('start_date', '2020-10-16T00:00:00.000Z') }}"
},
},
}
],
"spec": {
"connection_specification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["api_key"],
"properties": {
"api_key": {
"type": "string",
"title": "API Key",
"airbyte_secret": True,
},
"start_date": {
"title": "Start Date",
"description": "UTC date and time in the format YYYY-MM-DDTHH:MM:SS.000Z. During incremental sync, any data generated before this date will not be replicated. If left blank, the start date will be set to 2 years before the present date.",
"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$",
"pattern_descriptor": "YYYY-MM-DDTHH:MM:SS.000Z",
"examples": ["2020-11-16T00:00:00.000Z"],
"type": "string",
"format": "date-time",
},
},
"additionalProperties": True,
},
"documentation_url": "https://example.org",
"type": "Spec",
},
},
(
_create_page(
{
"rates": [
{"ABC": 0, "partition": 0, "updated_at": "2020-11-16T00:00:00.000Z"},
{"AED": 1, "partition": 0, "updated_at": "2020-11-16T00:00:00.000Z"},
],
"_metadata": {"next": "next"},
}
),
_create_page(
{
"rates": [
{"USD": 3, "partition": 0, "updated_at": "2020-11-16T00:00:00.000Z"}
],
"_metadata": {},
}
),
_create_page(
{
"rates": [
{"ABC": 2, "partition": 1, "updated_at": "2020-11-16T00:00:00.000Z"}
],
"_metadata": {},
}
),
),
2,
),
],
)
def test_slice_checkpoint(test_name, manifest, pages, expected_states_qty):
_stream_name = "Rates"
with patch.object(SimpleRetriever, "_fetch_next_page", side_effect=pages):
states = [message.state for message in _run_read(manifest, _stream_name) if message.state]
assert len(states) == expected_states_qty
76 changes: 76 additions & 0 deletions unit_tests/sources/streams/test_stream_read.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,82 @@ def test_incremental_read_two_slices():
assert len(actual_records) == len(expected_records)


@pytest.mark.parametrize(
"timestamp, records",
[
pytest.param(
"1708899428",
[
{"id": 2, "created_at": "1708899000"},
{"id": 3, "created_at": "1708899001"},
{"id": 4, "created_at": "1708899428"},
],
id="emits correct state when records are sorted by cursor",
),
pytest.param(
"1708899428",
[
{"id": 1, "created_at": "1708899428"},
{"id": 2, "created_at": "1708899000"},
{"id": 3, "created_at": "1708899001"},
{"id": 4, "created_at": "1708899002"},
],
id="emits correct state when records are not sorted by cursor",
),
pytest.param(
"1708899428",
[
{"id": 1, "created_at": "1708899428"},
{"id": 2, "created_at": "1708899000"},
{"id": 3, "created_at": "1708899428"},
{"id": 4, "created_at": "1708899002"},
],
id="not emit duplicated state",
),
],
)
def test_incremental_read_emit_state(timestamp, records):
# This test verifies that a stream running in incremental mode emits state messages correctly
configured_stream = ConfiguredAirbyteStream(
stream=AirbyteStream(
name="mock_stream",
supported_sync_modes=[SyncMode.full_refresh, SyncMode.incremental],
json_schema={},
),
sync_mode=SyncMode.incremental,
cursor_field=["created_at"],
destination_sync_mode=DestinationSyncMode.overwrite,
)
internal_config = InternalConfig()
logger = _mock_logger()
slice_logger = DebugSliceLogger()
message_repository = InMemoryMessageRepository(Level.INFO)
state_manager = ConnectorStateManager()
slice_to_partition = {1: records}
stream = _incremental_stream(
slice_to_partition, slice_logger, logger, message_repository, timestamp
)

expected_records = [
*records,
_create_state_message("__mock_incremental_stream", {"created_at": timestamp}),
]

actual_records = _read(
stream,
configured_stream,
logger,
slice_logger,
message_repository,
state_manager,
internal_config,
)

for record in expected_records:
assert record in actual_records
assert len(actual_records) == len(expected_records)


def test_concurrent_incremental_read_two_slices():
# This test verifies that an incremental concurrent stream manages state correctly for multiple slices syncing concurrently
configured_stream = ConfiguredAirbyteStream(
Expand Down
Loading