Skip to content

Fixes #29310: add TCP reachability preflight to database CheckAccess - #29308

Merged
chirag-madlani merged 12 commits into
mainfrom
feat/test-connection-network-preflight
Jun 29, 2026
Merged

chirag-madlani merged 12 commits into
mainfrom
feat/test-connection-network-preflight

Conversation

@IceS2

@IceS2 IceS2 commented Jun 22, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #29310

What

Adds a raw TCP reachability preflight to the database gate check. When a database connector's CheckAccess step runs (ping), it now opens a plain TCP connection to the engine's resolved host:port before the driver connection, so an unreachable host fails as a network problem rather than being tangled into a driver/TLS/auth error.

This separates the two failure classes a user actually needs distinguished:

  • TCP fails → DNS / firewall / wrong port / host down → network diagnosis, before any credentials are tried.
  • TCP succeeds but the query fails → auth / protocol / privileges → the connector's existing diagnosis.

How

  • core/connections/test_connection/network.py (new): tcp_probe(host, port, timeout) raising NetworkUnreachableError (chaining the underlying socket error), plus a NETWORK_ERRORS diagnosis pack. Diagnoses are keyed by exception type, not message, so they are driver- and platform-agnostic (e.g. ConnectionRefusedError regardless of errno 61 vs 111).
  • ErrorPack.including(other): immutable composition that appends another pack as a lower-precedence fallback — the connector's own rules still match first. Returns a new pack; the originals are untouched.
  • Matchers.exception(*types): type/cause-chain matcher used by NETWORK_ERRORS.
  • ping(): runs the preflight first, and skips it cleanly when the engine URL carries no host:port (file-based URLs like SQLite, connector-tunnelled engines).
  • MySQL: folds the network pack into its own via errors = MYSQL_ERRORS.including(NETWORK_ERRORS).

The probe lives in the shared ping() helper, so every database connector inherits reachability automatically as it migrates onto the new test-connection framework. The probe timeout is 20s (well under the 60s per-step budget, with headroom for slow / cross-region hosts).

Scope

Database connectors only for now — the path rides the shared ping() helper. network.py is category-neutral, so dashboard/messaging/pipeline checks can reuse tcp_probe / NETWORK_ERRORS when they land on the framework.

Tests

  • test_network.py (new): probe success against a live socket, refused-port → NetworkUnreachableError, and each diagnosis (DNS / refused / timeout / generic).
  • test_classifier.py: Matchers.exception chain matching, .including fallback ordering, precedence on overlap, and immutability of the original pack.
  • test_database_checks.py: ping skips the preflight without a host:port; unreachable host fails as a network error carrying the TCP-connect command.

75 tests pass across the framework + MySQL suites; ruff lint/format and basedpyright clean.

Greptile Summary

This PR adds a TCP reachability preflight check to the database CheckAccess (ping) step, so an unreachable host produces an actionable network error before any driver/TLS/auth logic is exercised. It introduces tcp_probe, NetworkUnreachableError, and a NETWORK_ERRORS diagnosis pack, and extends the classifier with Matchers.exception() (type-based chain matching) and ErrorPack.including() (immutable fallback composition).

  • network.py (new): tcp_probe wraps every OSError into NetworkUnreachableError; NETWORK_ERRORS uses NetworkUnreachableError as its catch-all (not bare OSError), so only preflight failures receive a "reachability" diagnosis and unrelated OSError subclasses from later steps are ignored.
  • classifier.py: Matchers.exception(*types) and ErrorPack.including(other) are added with correct immutability and precedence semantics, and the runner correctly passes failure.cause (the NetworkUnreachableError) to classify().
  • MySQL: folds NETWORK_ERRORS as a lower-precedence fallback; MySQL errno rules (e.g. 2013 for server-lost) still win over the network matchers for driver-level timeouts and connection drops.

Confidence Score: 5/5

Safe to merge. The preflight is cleanly gated on host+port presence, file-based and tunnelled engines skip it correctly, and the NetworkUnreachableError catch-all is scoped tightly enough that unrelated OSError subclasses from later steps are never misdiagnosed.

The key design risk — the catch-all rule misclassifying non-network OSErrors (BrokenPipeError, PermissionError) from later steps as reachability failures — has been explicitly avoided by keying the catch-all on NetworkUnreachableError rather than OSError. The runner correctly extracts failure.cause before calling classify(), so the NetworkUnreachableError carrying the original socket error reaches the pack as intended. MySQL errno rules (2003, 2013) are ordered before the NETWORK_ERRORS fallback, so driver-level connection/timeout errors still get their sharper diagnoses. Tests cover all four diagnosis branches, immutability of ErrorPack, cause-chain matching, and the critical isolation of non-preflight OSErrors.

No files require special attention.

Important Files Changed

Filename Overview
ingestion/src/metadata/core/connections/test_connection/network.py New module: tcp_probe + NETWORK_ERRORS pack. Catch-all correctly scoped to NetworkUnreachableError (not OSError), preventing misclassification of unrelated OS errors from later steps.
ingestion/src/metadata/core/connections/test_connection/checks/database.py ping() now calls _preflight() before run_sql(). Preflight is correctly gated on host and port being non-None, and file-based/tunnelled engines skip it cleanly.
ingestion/src/metadata/core/connections/test_connection/classifier.py Adds Matchers.exception() (type-chain matcher) and ErrorPack.including() (immutable composition). Both are correct and well-tested.
ingestion/src/metadata/ingestion/source/database/mysql/connection.py MySQLChecks.errors updated to MYSQL_ERRORS.including(NETWORK_ERRORS). MySQL errno rules (2003, 2013) take precedence over network matchers, avoiding misdiagnosis of driver-level failures.
ingestion/src/metadata/core/connections/test_connection/constants.py Adds NETWORK_PROBE_TIMEOUT_SECONDS = 20, well within the 60s step budget.
ingestion/tests/unit/core/connections/test_connection/test_network.py New test file covering probe success, refused port, and all four diagnosis branches including the critical isolation test for non-preflight OSErrors.
ingestion/tests/unit/core/connections/test_connection/test_classifier.py Extended with tests for Matchers.exception (type and chain matching), ErrorPack.including (precedence, fallback, immutability). All scenarios covered.
ingestion/tests/unit/core/connections/test_connection/test_database_checks.py Adds two new test cases: SQLite (no host:port, preflight skipped) and unreachable host (TCP connect fails as NetworkUnreachableError). Uses port-squatting helper with a minor TOCTOU race.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant Runner
    participant ping
    participant _preflight
    participant tcp_probe
    participant run_sql
    participant ErrorPack

    Runner->>ping: call check_access()
    ping->>_preflight: _preflight(client)
    _preflight->>_preflight: "host, port = client.url.host, client.url.port"
    alt host and port present
        _preflight->>tcp_probe: "tcp_probe(host, port, timeout=20s)"
        alt TCP connect succeeds
            tcp_probe-->>_preflight: None (ok)
        else OSError (DNS / refused / timeout)
            tcp_probe-->>_preflight: "raise NetworkUnreachableError(cause=OSError)"
            _preflight-->>ping: raise CheckError(NetworkUnreachableError, Evidence)
            ping-->>Runner: raise CheckError
            Runner->>ErrorPack: classify(NetworkUnreachableError)
            ErrorPack-->>Runner: Diagnosis
        end
    else no host:port (SQLite / tunnel)
        _preflight-->>ping: skip (return None)
    end
    ping->>run_sql: run_sql(client, SELECT 1, ...)
    alt query succeeds
        run_sql-->>ping: "Evidence(summary=connection established)"
        ping-->>Runner: Evidence
    else driver / auth / TLS error
        run_sql-->>ping: raise CheckError(cause, Evidence)
        ping-->>Runner: raise CheckError
        Runner->>ErrorPack: classify(cause)
        ErrorPack-->>Runner: Diagnosis (MySQL errno rules first, then NETWORK_ERRORS fallback)
    end
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant Runner
    participant ping
    participant _preflight
    participant tcp_probe
    participant run_sql
    participant ErrorPack

    Runner->>ping: call check_access()
    ping->>_preflight: _preflight(client)
    _preflight->>_preflight: "host, port = client.url.host, client.url.port"
    alt host and port present
        _preflight->>tcp_probe: "tcp_probe(host, port, timeout=20s)"
        alt TCP connect succeeds
            tcp_probe-->>_preflight: None (ok)
        else OSError (DNS / refused / timeout)
            tcp_probe-->>_preflight: "raise NetworkUnreachableError(cause=OSError)"
            _preflight-->>ping: raise CheckError(NetworkUnreachableError, Evidence)
            ping-->>Runner: raise CheckError
            Runner->>ErrorPack: classify(NetworkUnreachableError)
            ErrorPack-->>Runner: Diagnosis
        end
    else no host:port (SQLite / tunnel)
        _preflight-->>ping: skip (return None)
    end
    ping->>run_sql: run_sql(client, SELECT 1, ...)
    alt query succeeds
        run_sql-->>ping: "Evidence(summary=connection established)"
        ping-->>Runner: Evidence
    else driver / auth / TLS error
        run_sql-->>ping: raise CheckError(cause, Evidence)
        ping-->>Runner: raise CheckError
        Runner->>ErrorPack: classify(cause)
        ErrorPack-->>Runner: Diagnosis (MySQL errno rules first, then NETWORK_ERRORS fallback)
    end
Loading

Reviews (12): Last reviewed commit: "Merge branch 'main' into feat/test-conne..." | Re-trigger Greptile

The database gate check (CheckAccess -> ping) now runs a raw TCP connect to
the engine's resolved host:port before opening the driver connection. This
separates a network failure (DNS, firewall, wrong port) from an auth/protocol
failure: an unreachable host now fails as a network problem with an actionable
diagnosis, before TLS or credentials are exercised.

- core/connections/test_connection/network.py: tcp_probe + NetworkUnreachableError
  + NETWORK_ERRORS diagnosis pack, matched by exception type so it is driver-
  and platform-agnostic.
- ErrorPack.including(other): immutable compose that appends another pack as a
  lower-precedence fallback; connector rules still match first.
- Matchers.exception(*types): type/cause-chain matcher for socket errors.
- ping() skips the preflight when the engine URL has no host:port (file-based
  URLs, connector-tunnelled engines).
- MySQL folds NETWORK_ERRORS into its pack via .including(); every database
  connector inherits the preflight as it migrates onto the framework.
@IceS2
IceS2 requested a review from a team as a code owner June 22, 2026 13:38
@github-actions

github-actions Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

The linked issue has a description and all required Shipping project fields set. Thanks!

@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Jun 22, 2026
@IceS2 IceS2 changed the title feat(ingestion): add TCP reachability preflight to database CheckAccess Fixes #29310: add TCP reachability preflight to database CheckAccess Jun 22, 2026
Address review feedback on the test-connection network preflight:

- NETWORK_ERRORS catch-all now matches NetworkUnreachableError (which only
  tcp_probe raises) instead of a bare OSError. The error pack classifies every
  step, not just CheckAccess, so the OSError catch-all could mislabel an
  unrelated OS error (a dropped pipe, a permission error) from a later step as
  "Cannot reach the host". Scoping it to our own type makes that impossible;
  unrelated errors keep their raw errorLog.
- Document that ping()'s preflight assumes the driver connects directly to the
  URL host:port; connectors whose transport differs (HTTP gateway, load
  balancer, unix socket) should call run_sql() directly instead of ping().
- Add a regression test asserting an unrelated OSError is not classified as a
  reachability problem.
@github-actions

github-actions Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

🔴 Playwright Results — 2 failure(s), 52 flaky

✅ 4421 passed · ❌ 2 failed · 🟡 52 flaky · ⏭️ 39 skipped

Shard Passed Failed Flaky Skipped
🔴 Shard 1 317 1 6 5
🔴 Shard 2 819 1 9 9
🟡 Shard 3 823 0 6 7
🟡 Shard 4 826 0 5 10
🟡 Shard 5 857 0 17 0
🟡 Shard 6 779 0 9 8

Genuine Failures (failed on all attempts)

❌ Features/TagsSuggestion.spec.ts › should decline requested tags for an api endpoint request schema field (shard 1)
Error: �[2mexpect(�[22m�[31mlocator�[39m�[2m).�[22mtoBeVisible�[2m(�[22m�[2m)�[22m failed

Locator: locator('[data-testid="task-feed-card"]').filter({ hasText: '#31' }).first()
Expected: visible
Timeout: 15000ms
Error: element(s) not found

Call log:
�[2m  - Expect "toBeVisible" with timeout 15000ms�[22m
�[2m  - waiting for locator('[data-testid="task-feed-card"]').filter({ hasText: '#31' }).first()�[22m

❌ Features/GlobalSearchSuggestions.spec.ts › Navigate to column from column suggestion (shard 2)
�[31mTest timeout of 60000ms exceeded.�[39m
🟡 52 flaky test(s) (passed on retry)
  • Features/DataAssetRulesEnabled.spec.ts › Verify the Dashboard Entity Action items after rules is Enabled (shard 1, 1 retry)
  • Features/DataAssetRulesDisabled.spec.ts › Verify the Spreadsheet entity item action after rules disabled (shard 1, 1 retry)
  • Features/TagsSuggestion.spec.ts › should add and accept requested tags for an api endpoint request schema field (shard 1, 2 retries)
  • Features/TagsSuggestion.spec.ts › should edit and accept suggested tags for an api endpoint response schema field (shard 1, 2 retries)
  • Flow/SearchRBAC.spec.ts › the browse tree only shows the asset-type categories a user can access (shard 1, 1 retry)
  • Features/DomainIsolation/DomainLineageIsolation.spec.ts › userA sees tableA but not the cross-tenant tableB node (shard 1, 1 retry)
  • Features/BulkEditEntity.spec.ts › Database (shard 2, 1 retry)
  • Features/BulkEditEntity.spec.ts › Database Schema (shard 2, 1 retry)
  • Features/BulkImport.spec.ts › Database service (shard 2, 2 retries)
  • Features/BulkImport.spec.ts › Database Schema (shard 2, 1 retry)
  • Features/Container.spec.ts › expand / collapse should not appear after updating nested fields for container (shard 2, 1 retry)
  • Features/Container.spec.ts › Copy column link button should copy the column URL to clipboard (shard 2, 1 retry)
  • Features/DataQuality/ColumnLevelTests.spec.ts › Column Values To Match Regex (shard 2, 1 retry)
  • Features/DataQuality/TestCaseImportExportE2eFlow.spec.ts › Admin: Complete export-import-validate flow (shard 2, 2 retries)
  • Features/ExploreQuickFilters.spec.ts › explore tree sidebar selection is not cleared when a top dropdown filter is applied (shard 2, 1 retry)
  • Features/KnowledgeCenter.spec.ts › Verify Left Panel hierarchy pagination functionality (shard 3, 1 retry)
  • Features/Permissions/EntityPermissions.spec.ts › Spreadsheet allow common operations permissions (shard 3, 1 retry)
  • Features/RecentlyViewed.spec.ts › Check Pipeline in recently viewed (shard 3, 1 retry)
  • Features/RecentlyViewed.spec.ts › Check Topic in recently viewed (shard 3, 1 retry)
  • Features/SearchIndexNestedColumns.spec.ts › 25-level oversized nested column indexes and is searchable by its deep column name (shard 3, 1 retry)
  • Features/Table.spec.ts › Table pagination with sorting should works (shard 3, 1 retry)
  • Pages/CustomProperties.spec.ts › Integer (shard 4, 1 retry)
  • Pages/CustomProperties.spec.ts › Markdown (shard 4, 1 retry)
  • Pages/DataContracts.spec.ts › Create Data Contract and validate for MlModel (shard 4, 1 retry)
  • Pages/DataContracts.spec.ts › Contract Status badge should be visible on condition if Contract Tab is present/hidden by Persona (shard 4, 1 retry)
  • Pages/DomainAdvanced.spec.ts › Remove multiple assets from domain at once (shard 4, 1 retry)
  • Pages/Entity.spec.ts › Certification Add Remove (shard 5, 1 retry)
  • Pages/Entity.spec.ts › Follow & Un-follow entity (shard 5, 1 retry)
  • Pages/Entity.spec.ts › User should be denied access to edit description when deny policy rule is applied on an entity (shard 5, 1 retry)
  • Pages/Entity.spec.ts › Announcement create, edit & delete (shard 5, 1 retry)
  • ... and 22 more

📦 Download artifacts

How to debug locally
# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip    # view trace

@sonarqubecloud

Copy link
Copy Markdown

@gitar-bot

gitar-bot Bot commented Jun 29, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 1 resolved / 1 findings

Adds a TCP reachability preflight to the database CheckAccess flow to decouple network connectivity issues from driver-level errors. Resolved the potential for misleading error classification for post-access operations by successfully implementing an immutable error pack composition.

✅ 1 resolved
✅ Edge Case: TCP preflight may false-fail when driver path differs from URL host:port

📄 ingestion/src/metadata/core/connections/test_connection/checks/database.py:147-153 📄 ingestion/src/metadata/core/connections/test_connection/network.py:41-51
_preflight opens a raw TCP socket to client.url.host:client.url.port and converts any failure into a CheckError/NetworkUnreachableError, gating the real driver connection on direct reachability of that exact address.

This is correct for MySQL today (PyMySQL connects over TCP to the same host:port). However, the probe lives in the shared ping() helper and the PR states every database connector inherits it as it migrates. For connectors whose actual driver connection does NOT use a plain TCP socket to the URL's host:port — e.g. drivers that route through an HTTP(S) gateway/proxy, a load balancer, or a local unix socket while the URL still carries a host:port — a successful real connection could be preceded by a failing raw-TCP probe, turning a working connection into a spurious 'network unreachable' failure.

Since only MySQL is wired in now, impact is currently limited, but it's worth documenting/guarding before broader rollout (e.g. making the preflight opt-in per connector, or only probing when the driver is known to use direct TCP). At minimum, ensure each connector validates that its transport matches the probe assumption before adopting ping().

References: ingestion/src/metadata/core/connections/test_connection/checks/database.py:147-153, ingestion/src/metadata/core/connections/test_connection/network.py:41-51

Options

Display: compact → Showing less information.

Comment with these commands to change:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

This branch was previously deployed

1 inactive deployment
test — 084ee1cc Deployed Jun 29, 2026 by IceS2 via playwright-ci-postgresql (5, 6) #53602
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.

Database test connection should distinguish network-unreachable from auth failures

3 participants