Fast Snowflake Ingestion#
FastSnowflakeIngestion syncs data from Snowflake into a Foundry dataset from inside a Foundry lightweight transform.
It focuses on efficient, parallel file export/upload, without Spark and without a Data Connection agent.
It can be used to migrate existing Data Connection syncs to in-code solutions, but also for any new syncs, as long as the desired data is present on Snowflake.
The helper does not include data transformation utilities and expects users to prepare the data using a Snowpark DataFrame.
FSI requires snowflake-snowpark-python as an optional dependency, which is not installed with Foundry DevTools.
Add it to the dependencies of your lightweight transforms repository next to foundry-dev-tools.
Contents
Process overview#
Unloads a Snowpark DataFrame to Parquet files in a Snowflake stage.
Downloads the files to a local temporary directory.
Uploads files to a Foundry output via the filesystem in parallel.
Commits the dataset transaction.
Removes the local temporary directory.
The most important requirement is a Snowpark Session object, which can be obtained via transforms.tables.TableInput/TableLightweightInput.snowpark().session.
After obtaining a session and deciding whether the Snowflake database is shared or non-shared, the FastSnowflakeIngestion object can be created.
This object either runs the whole sync via save_snowpark_dataframe_to_foundry_output, or the single steps can be called one by one to customize the pipeline.
The recommended approach is save_snowpark_dataframe_to_foundry_output, which runs everything in a single call.
Limitations#
No built-in incremental ingestion.
No automatic type conversions; operates on the Snowpark DataFrame types you provide.
TIMESTAMP_TZandTIMESTAMP_LTZcolumns cannot be unloaded to Parquet, as Parquet has no type that stores a time zone (offset) per value. Cast these columns to another type before calling FSI, see Full table sync with timestamp-to-date casting and the Snowflake data unloading considerations.Intended for full or filtered table exports; does not transform data beyond what you do within Snowpark.
Only works inside a Foundry lightweight transform, as it uses the Foundry transforms runtime to commit the transaction.
Prerequisites#
A Snowpark session (e.g., via
transforms.tables.TableInput.snowpark().session).A Foundry transform Output.
If using a shared database stage:
Database name
Schema name
Permission to create a temporary stage in that schema
Quick start#
import snowflake.snowpark as snow
from transforms.api import LightweightContext, Output, lightweight, transform
from transforms.tables import TableInput
from foundry_dev_tools.helpers.fast_snowflake_ingestion import FastSnowflakeIngestion
@lightweight(cpu_cores=4, memory_gb=30)
@transform(
output=Output("foundry_output_path"),
virtual_table=TableInput("virtual_table_rid"),
)
def run_sync(ctx: LightweightContext, output: Output, virtual_table: TableInput):
session: snow.Session = virtual_table.snowpark().session
fsi = FastSnowflakeIngestion(
snowpark_session=session,
output=output,
provisioned_vcpus=4,
)
df = virtual_table.snowpark().dataframe()
# <optional Snowpark transformations, pushed down to and executed in Snowflake>
fsi.save_snowpark_dataframe_to_foundry_output(df)
Stage fallback#
When the primary stage setup fails (e.g., due to permission issues or stage unavailability), a fallback shared database stage can be used.
The fallback is only used when both fallback_db_name and fallback_schema_name are provided.
The stage is resolved during object initialization, so by the time the pipeline runs, a working stage is already in place.
The strategies are tried in order:
If
use_shared_db=True, try the user-provided DB/schema.If
use_shared_db=False, try the session’s default stage.If the above fails,
enable_automatic_stage_fallback=True(the default) and the fallback DB/schema are provided, tryfallback_db_name.fallback_schema_name.
Each strategy catches snowflake.connector.errors.Error.
A new random stage name is generated for the fallback to avoid collisions with the failed attempt.
If all attempted strategies fail, the snowflake.connector.errors.Error from the last attempt is raised during initialization.
# Fallback stage configured
fsi = FastSnowflakeIngestion(
snowpark_session=session,
output=output,
provisioned_vcpus=4,
fallback_db_name="FALLBACK_DB",
fallback_schema_name="STAGING",
)
# Fallback explicitly disabled, any stage setup failure raises immediately
fsi = FastSnowflakeIngestion(
snowpark_session=session,
output=output,
provisioned_vcpus=4,
fallback_db_name="FALLBACK_DB",
fallback_schema_name="STAGING",
enable_automatic_stage_fallback=False,
)
You can check whether the fallback stage is active via get_database_and_staging_info():
info = fsi.get_database_and_staging_info()
print(info["is_using_fallback"]) # True if fallback was activated
When the fallback activates, it creates a temporary stage in the fallback schema. The Snowflake role used by your session must have:
USAGEon the fallback databaseUSAGEon the fallback schemaCREATE STAGEon the fallback schema
S3 regional endpoint workaround#
By default, the constructor calls disable_s3_transfer_acceleration(), which monkeypatches the Snowflake connector’s SnowflakeS3RestClient.
This works around snowflake-connector-python#2317.
Problem#
Downloading the unloaded files (session.file.get) talks directly to the S3 bucket behind the internal stage.
Unless the Snowflake server tells the connector to use the regional endpoint (useS3RegionalUrl in the stage info),
the connector uses the global bucket endpoint https://<bucket>.s3.amazonaws.com.
Connector versions before 4.0.0 additionally call https://<bucket>.s3.amazonaws.com/?accelerate
to check whether S3 transfer acceleration is enabled. Version 4.0.0 skips this check for internal stages,
but still uses the global endpoint.
If the network only allows the Snowflake account and the regional bucket endpoint
https://<bucket>.s3.<region>.amazonaws.com, for example a Foundry network egress policy allowing only these hosts,
the download fails with an error like:
RequestExceedMaxRetryError: GET with url b'https://<bucket>.s3.amazonaws.com/?accelerate' failed for exceeding maximum retries
What the patch does#
_get_bucket_accelerate_configalways returnsFalse, so the?acceleratecall is never made.transfer_accelerate_configalways sets the regional endpoint and reports acceleration as disabled.
The patch applies process-wide to every SnowflakeS3RestClient. Because transfer_accelerate_config is replaced entirely,
it also overrides endpoints sent by the server (e.g. FIPS endpoints) and the connector’s China region handling.
To disable the patch, pass enable_s3_monkeypatch=False to the constructor.
Alternative without the patch#
In the issue above, setting the following account parameter made the server return the regional endpoint, after which downloads worked without the patch. Note that Snowflake does not document this parameter for this purpose, and the related private connectivity feature requires the Business Critical edition.
use role accountadmin;
alter account set ENABLE_INTERNAL_STAGES_PRIVATELINK = true;
Storing the session ID on Foundry#
save_snowpark_dataframe_to_foundry_output has an optional, enabled by default, save_session_id parameter.
If set to True, it saves a 0-byte file to the output, with the Snowflake session ID as part of the file name, e.g.:
_snowflake_session_metadata/788272638628742.txt
The session IDs can be retrieved with Foundry DevTools:
import re
import sys
import foundry_dev_tools
DATASET_RIDS = """
Place any text here, only valid dataset RIDs will be extracted.
ri.foundry.main.dataset.00000000-0000-0000-0000-000000000001
ri.foundry.main.dataset.00000000-0000-0000-0000-000000000002
"""
SESSION_METADATA_PREFIX = "_snowflake_session_metadata/"
DATASET_RID_PATTERN = re.compile(r"ri\.foundry\.main\.dataset\.[0-9a-f-]{36}")
def get_session_id(ctx: foundry_dev_tools.FoundryContext, dataset_rid: str) -> str | None:
try:
files = ctx.catalog.list_dataset_files(dataset_rid, logical_path=SESSION_METADATA_PREFIX)
except Exception as e:
print(f"{dataset_rid}: error listing files - {e}", file=sys.stderr)
return None
for entry in files:
path: str = entry.get("logicalPath", "")
if path.startswith(SESSION_METADATA_PREFIX) and path.endswith(".txt"):
return path.removeprefix(SESSION_METADATA_PREFIX).removesuffix(".txt")
return None
ctx = foundry_dev_tools.FoundryContext()
for rid in dict.fromkeys(DATASET_RID_PATTERN.findall(DATASET_RIDS)):
session_id = get_session_id(ctx, rid)
if session_id is None:
print(f"{rid}: no session ID found", file=sys.stderr)
else:
print(session_id)
Re-using the session for Foundry-to-Snowflake temporary tables#
The same Session can be used to create a temporary table on Snowflake within the same Foundry transaction.
This requires a shared database with schema and database names provided, as the stage setup calls use_database() and use_schema() on the session.
session: snow.Session = virtual_table.snowpark().session
fsi = FastSnowflakeIngestion(
snowpark_session=session,
output=out,
provisioned_vcpus=1,
use_shared_db=True,
db_name="DB_NAME",
schema_name="SCHEMA_NAME",
)
sample_pl: pl.DataFrame = sample.polars()
sample_snow_df: snow.DataFrame = session.create_dataframe(data=sample_pl.to_dicts(), schema=sample_pl.columns)
sample_snow_df.show(10)
This Snowpark DataFrame can be used within the same Foundry transaction until the session gets closed.
If creating the DataFrame fails with an error like the one below, the Snowflake role of your source most likely lacks the privilege to create temporary tables:
SQL compilation error:
Table 'SNOWPARK_TEMP_TABLE_XXXXXXXXXX' does not exist
Grant it with:
grant create temporary table on schema DB_NAME.SCHEMA_NAME to role "<SOURCE_ROLE>";