Repository navigation
fix(ingestion): chunk Snowflake ACCESS_HISTORY lineage by day to avoid query timeouts - #28329
Conversation
…d query timeouts Long lineage windows (e.g. queryLogDuration=180) ran the combined ACCESS_HISTORY x QUERY_HISTORY query as a single FLATTEN-heavy statement, which Snowflake cancels on a client/server timeout (57014). The whole run then emitted 0 edges because one try/except wrapped the entire query. - Chunk the [start, end] window into 1-day slices (ACCESS_HISTORY_CHUNK_DAYS), mirroring the usage connector, via _iter_lineage_date_windows(). - Move the per-query try/except inside _fetch_access_history_rows so one slow day warns and is skipped instead of aborting the run; counters accumulate across windows for a single summary log. - Add a QUERY_HISTORY date predicate (qh.START_TIME) so each chunk prunes the larger QUERY_HISTORY view instead of scanning it fully per chunk. - Add a debug log when an edge is skipped because a table is not found in OpenMetadata, naming the unresolved upstream/downstream side. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR improves the reliability of Snowflake lineage extraction when using the ACCOUNT_USAGE.ACCESS_HISTORY path by splitting long query windows into daily chunks, isolating failures per chunk, and further pruning the QUERY_HISTORY join to reduce scan scope and avoid timeouts.
Changes:
- Chunk ACCESS_HISTORY lineage extraction into 1-day windows and continue processing even if a single window fails.
- Add date predicates to the
QUERY_HISTORYside of the ACCESS_HISTORY lineage SQL for better pruning/performance. - Enhance debug logging for skipped edges due to unresolvable upstream/downstream tables, and add unit tests covering the new behavior.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
ingestion/src/metadata/ingestion/source/database/snowflake/lineage.py |
Implements per-day window iteration, per-window query execution with isolated error handling, and adds debug logs for unresolvable table edges. |
ingestion/src/metadata/ingestion/source/database/snowflake/queries.py |
Adds explicit date bounding for ACCESS_HISTORY and QUERY_HISTORY timestamps in the lineage SQL to reduce scan scope. |
ingestion/tests/unit/topology/database/test_snowflake_access_history_lineage.py |
Updates and adds unit tests validating QUERY_HISTORY pruning, daily chunking behavior, per-window failure isolation, and debug logs for skipped edges. |
| WHERE ah.QUERY_START_TIME | ||
| BETWEEN to_timestamp_ltz('{start_time}') AND to_timestamp_ltz('{end_time}') | ||
| AND qh.START_TIME | ||
| BETWEEN to_timestamp_ltz('{start_time}') AND to_timestamp_ltz('{end_time}') | ||
| AND qh.EXECUTION_STATUS = 'SUCCESS' |
…rops a lineage edge ACCESS_HISTORY is the authoritative lineage source; QUERY_HISTORY only enriches with query text. The INNER JOIN dropped an entire edge whenever the matching QUERY_HISTORY row was absent or filtered out. Switch to a LEFT JOIN (ACCESS_HISTORY preserved) so the edge survives with a null query text. - Time-prune predicate (qh.START_TIME) moves into the ON clause so it cannot eliminate ACCESS_HISTORY rows (also removes the boundary-skew miss risk). - EXECUTION_STATUS and the user filterCondition stay as real exclusions but apply only when a QUERY_HISTORY row exists (qh.QUERY_ID IS NULL OR ...). - Drop the dbt/OpenMetadata NOT LIKE noise filters: OM runs only read-only queries (no OBJECTS_MODIFIED, structurally excluded), and dbt lineage from ACCESS_HISTORY is Snowflake-computed and merges idempotently. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…N, not query history filterCondition now renders as a trailing WHERE on the final edge result, so users scope lineage by the database/schema of the tables involved (UPSTREAM_TABLE / DOWNSTREAM_TABLE FQNs), e.g. DOWNSTREAM_TABLE LIKE 'MYDB.%', rather than filtering QUERY_HISTORY columns. EXECUTION_STATUS stays in the source CTE as the only qh-scoped predicate. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…OIN ON clause EXECUTION_STATUS = 'SUCCESS' moves from a post-join WHERE guard into the LEFT JOIN ON clause, alongside the time prune. This drops the (qh.QUERY_ID IS NULL OR ...) guard entirely and leaves the CTE WHERE with only the authoritative ah.QUERY_START_TIME bound. All qh predicates now gate enrichment only and can never drop an ACCESS_HISTORY edge. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (1)
ingestion/src/metadata/ingestion/source/database/snowflake/queries.py:615
{filter_condition}is appended after joiningcolumn_edges_grouped ce, but bothteandceexposeUPSTREAM_TABLE/DOWNSTREAM_TABLEcolumns. A user predicate likeWHERE (DOWNSTREAM_TABLE LIKE 'MYDB.%')will be an ambiguous column reference in SQL (it could refer toteorce). To make this reliable, either qualify the expected columns (e.g., requirete.DOWNSTREAM_TABLE/te.UPSTREAM_TABLE), or apply the filter before the join (e.g., wraptable_edgesin a subquery/CTE that applies the filter, then LEFT JOINcolumn_edges_grouped).
AND te.DOWNSTREAM_TABLE = ce.DOWNSTREAM_TABLE
{filter_condition}
"""
)
SNOWFLAKE_COPY_HISTORY_LINEAGE = textwrap.dedent(
Halves the per-run round-trips versus 1-day chunks while keeping each query small enough to avoid Snowflake timeouts. Chunking tests now derive their window spans from ACCESS_HISTORY_CHUNK_DAYS so they stay correct if the default changes again. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses review feedback: the window-level try/except previously let one malformed cursor row abort the rest of that window. Extract per-row parsing into _parse_access_history_row(), which warns and skips a single bad row so the remaining rows in the window still yield. The outer try/except still isolates query/connection failures per window. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
🟡 Playwright Results — all passed (15 flaky)✅ 4240 passed · ❌ 0 failed · 🟡 15 flaky · ⏭️ 87 skipped
🟡 15 flaky test(s) (passed on retry)
How to debug locally# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip # view trace |
…nnection setting - Promote useAccessHistory + accessHistoryChunkSize from connectionOptions to first-class Snowflake connection fields (default ON, probe-gated fallback to the legacy query_history parser) - Wrap the ACCESS_HISTORY final SELECT so a user filterCondition referencing UPSTREAM_TABLE / DOWNSTREAM_TABLE is not an ambiguous column reference - Isolate per-row edge build, per-row COPY_HISTORY, and per-phase failures so a single bad row/window/phase never aborts the lineage run - Add a GetAccessHistory test-connection step (non-mandatory) that probes ACCOUNT_USAGE.ACCESS_HISTORY; clarify GetQueries as usage + legacy fallback - Group useAccessHistory / accessHistoryChunkSize under Advanced Config in the Snowflake connection form Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
✅ TypeScript Types Auto-UpdatedThe generated TypeScript types have been automatically updated based on JSON schema changes in this PR. |
Code Review ✅ ApprovedChunks Snowflake ACCESS_HISTORY lineage queries into 2-day windows to prevent timeouts and isolates per-row failures to ensure lineage completeness. This includes a transition to LEFT JOIN for QUERY_HISTORY and improved scoping for filter conditions. OptionsDisplay: compact → Showing less information. Comment with these commands to change:
Was this helpful? React with 👍 / 👎 | Gitar |
|
|
…d query timeouts (#28329) * fix(ingestion): chunk Snowflake ACCESS_HISTORY lineage by day to avoid query timeouts Long lineage windows (e.g. queryLogDuration=180) ran the combined ACCESS_HISTORY x QUERY_HISTORY query as a single FLATTEN-heavy statement, which Snowflake cancels on a client/server timeout (57014). The whole run then emitted 0 edges because one try/except wrapped the entire query. - Chunk the [start, end] window into 1-day slices (ACCESS_HISTORY_CHUNK_DAYS), mirroring the usage connector, via _iter_lineage_date_windows(). - Move the per-query try/except inside _fetch_access_history_rows so one slow day warns and is skipped instead of aborting the run; counters accumulate across windows for a single summary log. - Add a QUERY_HISTORY date predicate (qh.START_TIME) so each chunk prunes the larger QUERY_HISTORY view instead of scanning it fully per chunk. - Add a debug log when an edge is skipped because a table is not found in OpenMetadata, naming the unresolved upstream/downstream side. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(ingestion): LEFT JOIN QUERY_HISTORY so missing query text never drops a lineage edge ACCESS_HISTORY is the authoritative lineage source; QUERY_HISTORY only enriches with query text. The INNER JOIN dropped an entire edge whenever the matching QUERY_HISTORY row was absent or filtered out. Switch to a LEFT JOIN (ACCESS_HISTORY preserved) so the edge survives with a null query text. - Time-prune predicate (qh.START_TIME) moves into the ON clause so it cannot eliminate ACCESS_HISTORY rows (also removes the boundary-skew miss risk). - EXECUTION_STATUS and the user filterCondition stay as real exclusions but apply only when a QUERY_HISTORY row exists (qh.QUERY_ID IS NULL OR ...). - Drop the dbt/OpenMetadata NOT LIKE noise filters: OM runs only read-only queries (no OBJECTS_MODIFIED, structurally excluded), and dbt lineage from ACCESS_HISTORY is Snowflake-computed and merges idempotently. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(ingestion): scope ACCESS_HISTORY filterCondition by edge table FQN, not query history filterCondition now renders as a trailing WHERE on the final edge result, so users scope lineage by the database/schema of the tables involved (UPSTREAM_TABLE / DOWNSTREAM_TABLE FQNs), e.g. DOWNSTREAM_TABLE LIKE 'MYDB.%', rather than filtering QUERY_HISTORY columns. EXECUTION_STATUS stays in the source CTE as the only qh-scoped predicate. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(ingestion): move ACCESS_HISTORY success gate into the LEFT JOIN ON clause EXECUTION_STATUS = 'SUCCESS' moves from a post-join WHERE guard into the LEFT JOIN ON clause, alongside the time prune. This drops the (qh.QUERY_ID IS NULL OR ...) guard entirely and leaves the CTE WHERE with only the authoritative ah.QUERY_START_TIME bound. All qh predicates now gate enrichment only and can never drop an ACCESS_HISTORY edge. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * chore(ingestion): default ACCESS_HISTORY lineage chunk size to 2 days Halves the per-run round-trips versus 1-day chunks while keeping each query small enough to avoid Snowflake timeouts. Chunking tests now derive their window spans from ACCESS_HISTORY_CHUNK_DAYS so they stay correct if the default changes again. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(ingestion): isolate per-row parse failures in ACCESS_HISTORY window Addresses review feedback: the window-level try/except previously let one malformed cursor row abort the rest of that window. Extract per-row parsing into _parse_access_history_row(), which warns and skips a single bad row so the remaining rows in the window still yield. The outer try/except still isolates query/connection failures per window. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(ingestion): make Snowflake ACCESS_HISTORY lineage a permanent connection setting - Promote useAccessHistory + accessHistoryChunkSize from connectionOptions to first-class Snowflake connection fields (default ON, probe-gated fallback to the legacy query_history parser) - Wrap the ACCESS_HISTORY final SELECT so a user filterCondition referencing UPSTREAM_TABLE / DOWNSTREAM_TABLE is not an ambiguous column reference - Isolate per-row edge build, per-row COPY_HISTORY, and per-phase failures so a single bad row/window/phase never aborts the lineage run - Add a GetAccessHistory test-connection step (non-mandatory) that probes ACCOUNT_USAGE.ACCESS_HISTORY; clarify GetQueries as usage + legacy fallback - Group useAccessHistory / accessHistoryChunkSize under Advanced Config in the Snowflake connection form Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * Update generated TypeScript types --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>



Problem
Running Snowflake lineage with a large
queryLogDuration(e.g. 180 days) on the ACCESS_HISTORY path fails with:_yield_combined_access_historyrendered the entire window as oneACCESS_HISTORY × QUERY_HISTORYquery with multipleLATERAL FLATTENs over VARIANT arrays. Over a long window that single statement exceeds the clientnetwork_timeout/ server limits and Snowflake cancels it. Because the whole query sat in onetry/except, the run then emitted 0 edges.The
usageconnector already avoids this by scanning the window day-by-day — the lineage ACCESS_HISTORY path did not.Changes
Timeout fix — chunk the window
ACCESS_HISTORY_CHUNK_DAYS = 2) via_iter_lineage_date_windows(), mirroringSnowflakeUsageSource.yield_table_queries. Each chunk is a small, bounded query.try/exceptmoves into_fetch_access_history_rows()so one slow/failing day logs a warning (with the window bounds) and the run continues, instead of zeroing out the whole job. Counters accumulate across windows for a single summary log.Lineage completeness — LEFT JOIN QUERY_HISTORY
ACCESS_HISTORY is the authoritative lineage source (
DIRECT_OBJECTS_ACCESSED/OBJECTS_MODIFIEDand column-leveldirectSources); QUERY_HISTORY only contributes the query text. The previousINNER JOINdropped an entire edge whenever the matching QUERY_HISTORY row was absent or filtered out.LEFT JOIN(ACCESS_HISTORY preserved) so an edge survives with a null query text rather than vanishing.qh.START_TIMEtime-prune moves into theONclause — it bounds the QUERY_HISTORY scan per chunk (otherwise each daily query resolves itsQUERY_IDjoin against an unpruned QUERY_HISTORY) without being able to eliminate ACCESS_HISTORY rows. This also removes the boundary-skew miss risk anINNER JOINtime predicate would carry.EXECUTION_STATUS = 'SUCCESS'sits in theONclause too, so everyqhpredicate only gates enrichment and can never drop an ACCESS_HISTORY edge. The CTEWHEREcarries only the authoritativeah.QUERY_START_TIMEbound.NOT LIKEnoise filters: OM runs only read-only queries (noOBJECTS_MODIFIED, so structurally excluded), and dbt lineage from ACCESS_HISTORY is Snowflake-computed (not parsed) and merges idempotently with dbt-connector lineage.filterConditionnow scopes by table, not query historyOn the ACCESS_HISTORY path,
sourceConfig.filterConditionrenders as a trailingWHERE (...)on the final edge result instead of a predicate on QUERY_HISTORY. This lets you scope lineage by the database/schema of the tables involved via the edge columnsUPSTREAM_TABLE/DOWNSTREAM_TABLE(SnowflakeDB.SCHEMA.TABLEFQNs) — e.g.DOWNSTREAM_TABLE LIKE 'MYDB.%'orUPSTREAM_TABLE ILIKE 'MYDB.MYSCHEMA.%'. Note:qh.-qualified predicates are no longer valid on this path.COPY_HISTORY is left as a single query — it reads only the much smaller COPY_HISTORY view and is not the bottleneck.
Observability
skipped N (unresolvable ...)summary actionable.Test plan
test_snowflake_access_history_lineage.py(38 passing), including:test_combined_lineage_left_joins_query_history_to_keep_edges_without_texttest_combined_lineage_sql_prunes_query_history_by_datetest_access_history_chunks_window_by_day(3-day span → 3 queries with distinct bounds)test_access_history_window_failure_does_not_abort_runtest_table_edges_skip_when_either_side_unresolvableto assert the new debug logruff check+ruff format --checkclean on changed files.🤖 Generated with Claude Code
Summary by Gitar
openmetadata-uito reflect recent changes in service connection and ingestion pipeline schemas.This will update automatically on new commits.