Skip to content

fix(ingestion): chunk Snowflake ACCESS_HISTORY lineage by day to avoid query timeouts - #28329

Merged
ulixius9 merged 9 commits into
mainfrom
fix/snowflake-access-history-lineage-timeout
May 25, 2026
Merged

ulixius9 merged 9 commits into
mainfrom
fix/snowflake-access-history-lineage-timeout

Conversation

@ulixius9

@ulixius9 ulixius9 commented May 21, 2026 •

Copy link
Copy Markdown
Member

Problem

Running Snowflake lineage with a large queryLogDuration (e.g. 180 days) on the ACCESS_HISTORY path fails with:

000604 (57014): SQL execution was cancelled by the client due to a timeout

_yield_combined_access_history rendered the entire window as one ACCESS_HISTORY × QUERY_HISTORY query with multiple LATERAL FLATTENs over VARIANT arrays. Over a long window that single statement exceeds the client network_timeout / server limits and Snowflake cancels it. Because the whole query sat in one try/except, the run then emitted 0 edges.

The usage connector already avoids this by scanning the window day-by-day — the lineage ACCESS_HISTORY path did not.

Changes

Timeout fix — chunk the window

  • Chunk into 2-day slices (ACCESS_HISTORY_CHUNK_DAYS = 2) via _iter_lineage_date_windows(), mirroring SnowflakeUsageSource.yield_table_queries. Each chunk is a small, bounded query.
  • Per-window error isolation: the try/except moves 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_MODIFIED and column-level directSources); QUERY_HISTORY only contributes the query text. The previous INNER JOIN dropped an entire edge whenever the matching QUERY_HISTORY row was absent or filtered out.

  • Switch to LEFT JOIN (ACCESS_HISTORY preserved) so an edge survives with a null query text rather than vanishing.
  • The qh.START_TIME time-prune moves into the ON clause — it bounds the QUERY_HISTORY scan per chunk (otherwise each daily query resolves its QUERY_ID join against an unpruned QUERY_HISTORY) without being able to eliminate ACCESS_HISTORY rows. This also removes the boundary-skew miss risk an INNER JOIN time predicate would carry.
  • EXECUTION_STATUS = 'SUCCESS' sits in the ON clause too, so every qh predicate only gates enrichment and can never drop an ACCESS_HISTORY edge. The CTE WHERE carries only the authoritative ah.QUERY_START_TIME bound.
  • Drop the dbt / OpenMetadata NOT LIKE noise filters: OM runs only read-only queries (no OBJECTS_MODIFIED, so structurally excluded), and dbt lineage from ACCESS_HISTORY is Snowflake-computed (not parsed) and merges idempotently with dbt-connector lineage.

filterCondition now scopes by table, not query history

On the ACCESS_HISTORY path, sourceConfig.filterCondition renders as a trailing WHERE (...) 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 columns UPSTREAM_TABLE / DOWNSTREAM_TABLE (Snowflake DB.SCHEMA.TABLE FQNs) — e.g. DOWNSTREAM_TABLE LIKE 'MYDB.%' or UPSTREAM_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

  • When an edge is skipped because a table is not found in OpenMetadata, log at DEBUG which side (upstream/downstream) failed and the Snowflake table name — making the skipped N (unresolvable ...) summary actionable.

Test plan

  • Unit tests in test_snowflake_access_history_lineage.py (38 passing), including:
    • test_combined_lineage_left_joins_query_history_to_keep_edges_without_text
    • test_combined_lineage_sql_prunes_query_history_by_date
    • test_access_history_chunks_window_by_day (3-day span → 3 queries with distinct bounds)
    • test_access_history_window_failure_does_not_abort_run
    • extended test_table_edges_skip_when_either_side_unresolvable to assert the new debug log
  • ruff check + ruff format --check clean on changed files.

🤖 Generated with Claude Code


Summary by Gitar

  • Generated types:
    • Updated TypeScript definitions in openmetadata-ui to reflect recent changes in service connection and ingestion pipeline schemas.

This will update automatically on new commits.

…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]>
@ulixius9
ulixius9 requested a review from a team as a code owner May 21, 2026 07:17
Copilot AI review requested due to automatic review settings May 21, 2026 07:17
@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels May 21, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_HISTORY side 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.

Comment on lines 548 to 552
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]>
Copilot AI review requested due to automatic review settings May 21, 2026 07:46
…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]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 joining column_edges_grouped ce, but both te and ce expose UPSTREAM_TABLE/DOWNSTREAM_TABLE columns. A user predicate like WHERE (DOWNSTREAM_TABLE LIKE 'MYDB.%') will be an ambiguous column reference in SQL (it could refer to te or ce). To make this reliable, either qualify the expected columns (e.g., require te.DOWNSTREAM_TABLE/te.UPSTREAM_TABLE), or apply the filter before the join (e.g., wrap table_edges in a subquery/CTE that applies the filter, then LEFT JOIN column_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]>
IceS2
IceS2 previously approved these changes May 21, 2026
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]>
Copilot AI review requested due to automatic review settings May 21, 2026 08:52
@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

🟡 Playwright Results — all passed (15 flaky)

✅ 4240 passed · ❌ 0 failed · 🟡 15 flaky · ⏭️ 87 skipped

Shard Passed Failed Flaky Skipped
🟡 Shard 1 298 0 1 4
🟡 Shard 2 802 0 1 8
🟡 Shard 3 796 0 4 8
🟡 Shard 4 836 0 5 12
🟡 Shard 5 718 0 1 47
🟡 Shard 6 790 0 3 8
🟡 15 flaky test(s) (passed on retry)
  • Flow/SearchRBAC.spec.ts › User without permission (shard 1, 1 retry)
  • Features/Glossary/GlossaryWorkflow.spec.ts › should display correct status badge color and icon (shard 2, 1 retry)
  • Features/OntologyExplorerCardinality.spec.ts › stats reflect the cardinality-typed edges in the relation count (shard 3, 1 retry)
  • Features/OntologyExplorerE2E.spec.ts › switching back from Hierarchy to Overview restores stats (shard 3, 2 retries)
  • Features/OntologyExplorerE2E.spec.ts › toggling edge labels off and back on leaves the graph and cardinality map intact (shard 3, 1 retry)
  • Features/Table.spec.ts › Table pagination with sorting should works (shard 3, 1 retry)
  • Flow/PersonaFlow.spec.ts › Set default persona for team should work properly (shard 4, 1 retry)
  • Pages/CustomProperties.spec.ts › Table (shard 4, 1 retry)
  • Pages/CustomProperties.spec.ts › Email (shard 4, 1 retry)
  • Pages/CustomProperties.spec.ts › Should display custom properties for apiCollection in right panel (shard 4, 1 retry)
  • Pages/CustomProperties.spec.ts › Entity Reference (shard 4, 1 retry)
  • Pages/ExplorePageRightPanel_KnowledgeCenter.spec.ts › Should remove user owner for knowledgeCenter (shard 5, 1 retry)
  • Features/AutoPilot.spec.ts › Agents created by AutoPilot should be deleted (shard 6, 1 retry)
  • Pages/ExploreTree.spec.ts › Explore Tree (shard 6, 1 retry)
  • Pages/Lineage/LineageFilters.spec.ts › Verify lineage schema filter selection (shard 6, 1 retry)

📦 Download artifacts

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]>
@ulixius9
ulixius9 requested a review from a team as a code owner May 22, 2026 10:42
@github-actions

Copy link
Copy Markdown
Contributor

✅ TypeScript Types Auto-Updated

The generated TypeScript types have been automatically updated based on JSON schema changes in this PR.

Copilot AI review requested due to automatic review settings May 22, 2026 10:48
@ulixius9
ulixius9 removed the request for review from Copilot May 22, 2026 10:48
@github-actions

github-actions Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 63%
63.18% (65635/103884) 43.9% (35996/81988) 46.59% (10559/22661)

Copilot AI review requested due to automatic review settings May 22, 2026 11:33
@gitar-bot

gitar-bot Bot commented May 22, 2026 •

Copy link
Copy Markdown
Code Review ✅ Approved

Chunks 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.

Options

Display: compact → Showing less information.

Comment with these commands to change:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 19 changed files in this pull request and generated 2 comments.

@sonarqubecloud

Copy link
Copy Markdown

@sonarqubecloud

Copy link
Copy Markdown

@ulixius9
ulixius9 merged commit 580025c into main May 25, 2026
70 checks passed
@ulixius9
ulixius9 deleted the fix/snowflake-access-history-lineage-timeout branch May 25, 2026 10:59
ulixius9 added a commit that referenced this pull request May 25, 2026
…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>

This branch was previously deployed

1 inactive deployment
test — 68f4bd68 Deployed May 22, 2026 by ulixius9 via playwright-ci-postgresql (3, 6) #48249
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Ingestion safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants