foundry_dev_tools.helpers.fast_snowflake_ingestion package#

Fast Snowflake to Foundry ingestion for lightweight transforms, requires the snowflake extra.

class foundry_dev_tools.helpers.fast_snowflake_ingestion.FastSnowflakeIngestion[source]#

Bases: object

Initializes a FastSnowflakeIngestion instance with connection and staging info.

Parameters:
  • snowpark_session – Active Snowpark Session object.

  • output – Foundry transform Output.

  • provisioned_vcpus – Number of vCPUs to provision for parallel operations. Defaults to 4.

  • custom_tags – any custom tags a user wants the session to store. As JSON-like kwargs.

  • use_shared_db – Whether to use a shared database with custom stage. Defaults to False.

  • db_name – The name of the Snowflake database to use. Required when use_shared_db=True.

  • schema_name – The schema name within the database. Required when use_shared_db=True.

  • enable_automatic_stage_fallback – Whether to attempt a fallback to the shared database fallback_db_name.fallback_schema_name when the primary stage setup fails. Only takes effect if both fallback names are provided. Defaults to True.

  • fallback_db_name – The Snowflake database used for the fallback stage.

  • fallback_schema_name – The schema within fallback_db_name used for the fallback stage.

  • enable_s3_monkeypatch – Whether to call disable_s3_transfer_acceleration() before any stage operation. Defaults to True.

Raises:

ValueError – If use_shared_db=True but db_name or schema_name are not provided, or if only one of fallback_db_name and fallback_schema_name is provided.

Examples

# Using session stage (non-shared database): >>> fsi = FastSnowflakeIngestion( … snowpark_session=session, … output=out, … )

# Using shared database with custom stage: >>> fsi = FastSnowflakeIngestion( … snowpark_session=session, … output=out, … db_name=”SHARED_DB”, … schema_name=”EXPORT_SCHEMA”, … use_shared_db=True, … )

# With a fallback stage: >>> fsi = FastSnowflakeIngestion( … snowpark_session=session, … output=out, … fallback_db_name=”FALLBACK_DB”, … fallback_schema_name=”STAGING”, … )

# Adding custom session tags: >>> fsi = FastSnowflakeIngestion( … snowpark_session=session, … output=out, … custom_tags = { … “custom_snowflake_tag_1”: “my telemetry tag value 1”, … “custom_snowflake_tag_2”: { … “custom_nested_snowflake_tag_1”: 123, … “custom_nested_snowflake_tag_2”: [“A”, “B”, “C”], … } … } … )

__init__(snowpark_session, output, provisioned_vcpus=4, custom_tags=None, use_shared_db=False, db_name=None, schema_name=None, enable_automatic_stage_fallback=True, fallback_db_name=None, fallback_schema_name=None, enable_s3_monkeypatch=True)[source]#

Initializes a FastSnowflakeIngestion instance with connection and staging info.

Parameters:
  • snowpark_session (snow.Session) – Active Snowpark Session object.

  • output (Output) – Foundry transform Output.

  • provisioned_vcpus (int) – Number of vCPUs to provision for parallel operations. Defaults to 4.

  • custom_tags (dict[str, Any] | None) – any custom tags a user wants the session to store. As JSON-like kwargs.

  • use_shared_db (bool) – Whether to use a shared database with custom stage. Defaults to False.

  • db_name (str | None) – The name of the Snowflake database to use. Required when use_shared_db=True.

  • schema_name (str | None) – The schema name within the database. Required when use_shared_db=True.

  • enable_automatic_stage_fallback (bool) – Whether to attempt a fallback to the shared database fallback_db_name.fallback_schema_name when the primary stage setup fails. Only takes effect if both fallback names are provided. Defaults to True.

  • fallback_db_name (str | None) – The Snowflake database used for the fallback stage.

  • fallback_schema_name (str | None) – The schema within fallback_db_name used for the fallback stage.

  • enable_s3_monkeypatch (bool) – Whether to call disable_s3_transfer_acceleration() before any stage operation. Defaults to True.

Raises:

ValueError – If use_shared_db=True but db_name or schema_name are not provided, or if only one of fallback_db_name and fallback_schema_name is provided.

Examples

# Using session stage (non-shared database): >>> fsi = FastSnowflakeIngestion( … snowpark_session=session, … output=out, … )

# Using shared database with custom stage: >>> fsi = FastSnowflakeIngestion( … snowpark_session=session, … output=out, … db_name=”SHARED_DB”, … schema_name=”EXPORT_SCHEMA”, … use_shared_db=True, … )

# With a fallback stage: >>> fsi = FastSnowflakeIngestion( … snowpark_session=session, … output=out, … fallback_db_name=”FALLBACK_DB”, … fallback_schema_name=”STAGING”, … )

# Adding custom session tags: >>> fsi = FastSnowflakeIngestion( … snowpark_session=session, … output=out, … custom_tags = { … “custom_snowflake_tag_1”: “my telemetry tag value 1”, … “custom_snowflake_tag_2”: { … “custom_nested_snowflake_tag_1”: 123, … “custom_nested_snowflake_tag_2”: [“A”, “B”, “C”], … } … } … )

save_snowpark_dataframe_to_foundry_output(df, save_session_id=True, **kwargs)[source]#

Orchestrates the complete process of saving a Snowpark DataFrame to a Foundry output.

The local temporary directory is removed afterwards, also on failure.

Parameters:
  • df (snow.DataFrame) – The DataFrame to save.

  • save_session_id (bool) – Whether to save current Snowpark.Session.session_id to the Output as a 0-byte file as part of the file name. Defaults to True.

  • **kwargs – Additional arguments passed to underlying functions.

Keyword Arguments:
  • write_df_into_location_parquet() (For) –

    header (bool): Whether to include a header row. Default: True. format_type_options (dict): Format-specific options for Parquet.

    explain_df (bool): Whether to print the DataFrame’s execution plan. Default: False. copy_options (dict): Additional COPY options.

  • upload_temp_folder_to_output_dataset() (For) – output (Output): Will be used from the class object. path_files (list): List of file paths. Default: None (uses all files). cpu_cores (int): Number of CPU cores to use for upload. Default: provisioned_vcpus.

  • commit_dataset_upload() (For) – column_descriptions (dict): Column descriptions to add to the final dataset.

Return type:

bool

Example:

>>> kwargs_example = {
...     "header": True,
...     "format_type_options": {
...         "COMPRESSION": "AUTO",
...         "SNAPPY_COMPRESSION": True,
...     },
...     "explain_df": False,
...     "copy_options": {
...         "OVERWRITE": True,
...         "SINGLE": False,
...         "MAX_FILE_SIZE": 200 * 1024 * 1024,
...         "INCLUDE_QUERY_ID": False,
...         "DETAILED_OUTPUT": True
...     },
...     "path_files": None,
...     "cpu_cores": 4,
...     "column_descriptions": {
...         "column1": "Description for column 1",
...         "column2": "Description for column 2",
...         "timestamp_col": "Timestamp when record was created"
...     }
... }
>>> success = fsi.save_snowpark_dataframe_to_foundry_output(
...     df=my_df, **kwargs_example
... )
Returns:

Always True, any failure raises an exception instead.

Return type:

bool

Raises:
  • snowflake.connector.errors.Error – If the write or download step fails.

  • Exception – If any other step in the process fails.

Parameters:
  • df (snow.DataFrame)

  • save_session_id (bool)

get_database_and_staging_info()[source]#

Provides comprehensive metadata about the database type and staging configuration.

Returns detailed information about whether a shared or non-shared database approach is being used, along with all relevant staging parameters.

Returns:

A dictionary containing:
  • use_shared_db: Boolean indicating shared vs non-shared database mode

  • db_name: The database in use, None when the session stage is used

  • schema_name: The schema in use, None when the session stage is used

  • fully_qualified_stage_name: Full stage name (None for non-shared mode)

  • temporary_stage_name: Name of the temporary stage, dropped by Snowflake at session end

  • remote_file_path: Complete path for file operations

  • is_using_fallback: Whether the fallback stage is currently active

Return type:

dict

get_snowpark_session()[source]#

Returns the Snowpark session associated with this ingestion instance.

Return type:

snow.Session

write_df_into_location_parquet(df, remote_file_path, header=True, format_type_options=None, copy_options=None, explain_df=False)[source]#

Writes a Snowpark DataFrame to a specified remote Snowflake stage location as Parquet.

TIMESTAMP_TZ and TIMESTAMP_LTZ columns cannot be unloaded to Parquet, as Parquet has no type that stores a time zone (offset) per value. Cast them to TIMESTAMP_NTZ (drops the offset) or DATE (also drops the time of day) before calling this method.

Parameters:
  • df (snow.DataFrame) – The DataFrame to write.

  • remote_file_path (str) – The destination path in the Snowflake stage.

  • header (bool) – Whether to include a header row. Defaults to True.

  • format_type_options (dict[str, str] | None) – Format-specific options for Parquet. Defaults to AUTO compression.

  • copy_options (dict[str, Any] | None) – Additional COPY options. Defaults to standard options with 200MB max file size.

  • explain_df (bool) – Whether to print the DataFrame’s execution plan. Defaults to False.

Returns:

A list of Row objects containing unloading results.

Return type:

list[snow.Row]

download_snowflake_files_to_foundry_tmp_folder()[source]#

Downloads files from the Snowflake stage to a temporary local directory.

Returns:

List of results from the file download operation.

Return type:

list[snow.GetResult]

cleanup_temp_dir()[source]#

Removes the local temporary directory created by the download step, if any.

Return type:

None

get_files_from_temp_dir()[source]#

Lists all files in the temporary directory created during download.

Returns:

List of filenames in the temp directory.

Raises:

RuntimeError – If the temp directory has not been created.

Return type:

list[str]

get_path_files(files=None)[source]#

Maps file names in the temp directory to their full paths.

Parameters:

files (list[str] | None) – Specific list of filenames to include. If not provided, uses all files in the temp directory.

Returns:

List of file pathlib.Path.

Return type:

list[Path]

upload_temp_folder_to_output_dataset(output, path_files=None, cpu_cores=None)[source]#

Iterates through a list of file paths and calls the upload_file function for each.

Uploads in parallel with a ThreadPoolExecutor if there is more than 1 file and more than 1 CPU.

Parameters:
  • output (Output) – the transform output

  • path_files (list[Path] | None) – the files to upload, defaults to all files in the temp directory

  • cpu_cores (int | None) – amount of cores provisioned for the transform. The function will use N-1 or 1 CPUs depending which is greater.

Return type:

None

save_session_id_to_output()[source]#

Saves current Snowpark.Session.session_id to the Output filesystem.

The session id is part of the file name, the file is 0 bytes in size. Does not commit any transactions.

Return type:

None

set_session_query_tag(**custom_tags)[source]#

Sets the Snowpark session query tag to Foundry job telemetry data combined with custom tags.

For an example of the job info, see foundry_dev_tools.helpers.fast_snowflake_ingestion.utils.prepare_job_info().

Snowflake limits QUERY_TAG to 2000 characters. A longer tag is truncated to that limit (it is then no longer valid JSON, but still usable for substring matching) and the full tag is logged.

Parameters:

**custom_tags – optional, additional custom tags.

Return type:

None

static upload_file(output, file_path, base_dir=None)[source]#

Uploads a single file using filesystem to the Transform’s output.

Parameters:
  • output (Output) – the transform output

  • file_path (Path) – full path to the file supposed to be uploaded

  • base_dir (Path | None) – the directory the destination path is relative to. If None, the destination is the path below the first directory under the system temp directory.

Return type:

None

static commit_dataset_upload(dataset_rid, branch_id, transaction_rid, column_descriptions=None)[source]#

Commits the dataset upload transaction to finalize the data ingestion.

Only available inside a Foundry lightweight transform.

Parameters:
  • dataset_rid (str) – The dataset RID.

  • branch_id (str) – The branch ID.

  • transaction_rid (str) – The transaction RID.

  • column_descriptions (dict[str, str] | None) – Column descriptions to add to the dataset. Defaults to empty dict.

Return type:

None

class foundry_dev_tools.helpers.fast_snowflake_ingestion.FoundryPathWithBranchId[source]#

Bases: object

A FoundryPath together with a branch id.

__init__(foundry_path, branch_id)[source]#
Parameters:
property foundry_path: TransactionPath | ViewPath#

The foundry path.

property branch_id: str | None#

The branch id.

class foundry_dev_tools.helpers.fast_snowflake_ingestion.TransactionPath[source]#

Bases: object

Path to a dataset transaction, usable without importing Foundry internal classes.

__init__(dataset_rid, transaction_rid, logical_path=None)[source]#
Parameters:
  • dataset_rid (str)

  • transaction_rid (str)

  • logical_path (str | None)

property dataset_rid: str#

The dataset rid.

property transaction_rid: str#

The transaction rid.

property end_ref: str#

The end ref, which is the transaction rid.

class foundry_dev_tools.helpers.fast_snowflake_ingestion.ViewPath[source]#

Bases: object

Path to a dataset view, usable without importing Foundry internal classes.

__init__(dataset_rid, end_ref, start_transaction=None, logical_path=None)[source]#
Parameters:
  • dataset_rid (str)

  • end_ref (str)

  • start_transaction (str | None)

  • logical_path (str | None)

property dataset_rid: str#

The dataset rid.

property end_ref: str#

The end ref of the view.

foundry_dev_tools.helpers.fast_snowflake_ingestion.disable_s3_transfer_acceleration()[source]#

Forces the regional S3 endpoint in the Snowflake connector, by monkeypatching SnowflakeS3RestClient.

Workaround for snowflakedb/snowflake-connector-python#2317.

Problem: unless the server sends useS3RegionalUrl/useRegionalUrl in the stage info, the connector uses the global bucket endpoint https://<bucket>.s3.amazonaws.com for internal stages. Connector versions before 4.0.0 additionally call https://<bucket>.s3.amazonaws.com/?accelerate to check whether S3 transfer acceleration is enabled for the bucket (4.0.0 skips this for internal stages, but still uses the global endpoint). In networks where only the Snowflake account and the regional bucket endpoint https://<bucket>.s3.<region>.amazonaws.com are reachable (e.g. a Foundry network egress policy allowing only these hosts), stage file transfers (GET/PUT, e.g. session.file.get) fail with:

RequestExceedMaxRetryError: GET with url b'https://<bucket>.s3.amazonaws.com/?accelerate'
failed for exceeding maximum retries

The regional endpoint also keeps the transfer cheap. When the Snowflake account (and therefore its internal stage bucket) runs in the same AWS region as the Foundry instance, Foundry can reach the bucket privately: its Control Panel sets up an AWS S3 gateway endpoint for a “same region S3 bucket policy” network egress policy, which allows the regional bucket host. Traffic through an S3 gateway endpoint stays on the AWS network and AWS charges nothing for it, neither for the endpoint nor for the data transferred between AWS services and S3 within the same region. Gateway endpoints only work within their own region, so a stage bucket in a different region than Foundry does not get this benefit. References:

The patch replaces two methods of SnowflakeS3RestClient:

  • _get_bucket_accelerate_config always returns False, so the ?accelerate call is never made.

  • transfer_accelerate_config always sets the regional endpoint and reports acceleration as disabled.

Side effects: the patch is applied process-wide to every SnowflakeS3RestClient, calling it more than once is harmless. As transfer_accelerate_config is replaced entirely, endpoints sent by the server (e.g. FIPS endpoints) and the connector’s China region handling (.amazonaws.com.cn) are overridden as well. Disable it via enable_s3_monkeypatch=False in FastSnowflakeIngestion if that is a problem.

Alternatively, setting the account parameter below made the server return the regional endpoint, so the patch is not needed (confirmed in the issue above, not documented by Snowflake for this purpose, the related private connectivity feature requires the Business Critical edition):

use role accountadmin;
alter account set ENABLE_INTERNAL_STAGES_PRIVATELINK = true;
Return type:

None

Submodules#