Skip to content

Fixes #29341: migrate Postgres test connection to the @check framework - #29342

Merged
chirag-madlani merged 17 commits into
mainfrom
feat/postgres-test-connection-framework
Jul 8, 2026
Merged

chirag-madlani merged 17 commits into
mainfrom
feat/postgres-test-connection-framework

Conversation

@IceS2

@IceS2 IceS2 commented Jun 23, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #29341

Draft — stacked on #29308 (the TCP reachability preflight). Held until #29308 merges; until then this diff also contains #29308's commits.

What

Migrates PostgreSQL's test connection from the legacy test_connection_steps to the new @check / ChecksProvider framework (the path MySQL uses) — structured per-step diagnoses plus the shared TCP preflight that separates a network failure from an auth failure.

How

  • PostgresChecks implements all 10 seeded steps as @check methods, reusing the shared ping/run_sql/list_* helpers. No new shared abstraction — earned only when a second connector reuses one.

  • POSTGRES_ERRORS, validated live against PostgreSQL 15:

    Failure Signal Diagnosis
    bad password / unknown role message Authentication failed
    missing database message (quoted database "…") Database not found
    insufficient privilege SQLSTATE 42501 Insufficient privileges
    missing query history source SQLSTATE 42P01 Query history source not found
    no pg_hba.conf entry message Connection not permitted by pg_hba.conf
    unreachable host/port TCP preflight network diagnosis (via .including(NETWORK_ERRORS))
  • postgres.json: CheckAccess now category: ConnectionGate. The new runner gates on category, not the legacy shortCircuit flag — without it a failed CheckAccess didn't short-circuit, so every later step opened its own connection and an unreachable host hung ~9 min instead of failing at the ~20s preflight (545s → 20s, measured).

  • Connect-phase vs query-phase: psycopg2 sets SQLSTATE only on query-execution errors, so auth / database-not-found match on message text, query-phase (privilege, missing source) on SQLSTATE. The query-history source is keyed on 42P01 so it holds for any queryStatementSource, not just pg_stat_statements.

  • No eager connect: the GetQueries version-probe query is built inside the check, not at checks() construction, so nothing connects ahead of the gate. _get_client registers engine.dispose. Adds GetColumnMetadata/GetTableComments/GetInformationSchemaColumns to the shared DatabaseStep enum.

Greptile Summary

This PR migrates PostgreSQL's test-connection implementation from the legacy test_connection_db_common path to the new @check/ChecksProvider framework, aligning it with the pattern already used by MySQL. The key behavioral improvement is a TCP preflight in CheckAccess that separates network failures from auth/database failures in under 20s instead of waiting ~9 minutes per step.

  • PostgresChecks implements all 10 steps as @check methods. Error classification splits into message-text matchers for connect-phase errors (which carry no SQLSTATE in psycopg2) and SQLSTATE matchers for query-phase errors, plus shared NETWORK_ERRORS appended via .including().
  • postgres.json adds "category": "ConnectionGate" to CheckAccess (alongside the legacy shortCircuit: true) so the new runner can gate on Category.ConnectionGate without breaking older runners.
  • get_postgres_time_column_name is invoked inside get_queries() (not at PostgresChecks.__init__ time), keeping the version-probe query behind the gate and avoiding an eager connection at construction.

Confidence Score: 5/5

Safe to merge — the change is a well-scoped migration that removes legacy test-connection code and replaces it with a structured, gated framework, with no regressions in the engine-building or auth strategies.

The error-classification matchers are correctly ordered (message-text first for connect-phase errors that carry no SQLSTATE, SQLSTATE next for query-phase errors, network errors last). The _pgcode helper uses explicit is None guards. The TCP preflight is correctly placed behind the ConnectionGate so an unreachable host fails fast. The version-probe query is built lazily inside get_queries(), verified by a dedicated regression test. postgres.json adds "category": "ConnectionGate" which is a valid enum value per the JSON schema and is backward-compatible with the retained shortCircuit: true for older runners. Test coverage is thorough, including real psycopg2 message strings captured from PostgreSQL 15.

No files require special attention.

Important Files Changed

Filename Overview
ingestion/src/metadata/ingestion/source/database/postgres/connection.py Full replacement of the legacy test_connection with PostgresChecks. Error matchers are well-ordered (message text for connect-phase, SQLSTATE for query-phase, network last). _pgcode correctly uses is None guards. Engine disposal registered via _on_close. No issues found.
ingestion/src/metadata/core/connections/test_connection/checks/database.py Adds GetColumnMetadata, GetTableComments, GetInformationSchemaColumns to DatabaseStep enum so PostgresChecks can reference them as @check targets. Additive-only change, no issues.
ingestion/tests/unit/source/database/postgres/test_connection.py Adds 13 new test functions covering error classification (auth, DB-not-found, role, privilege, 42P01, pg_hba, network), step coverage, lazy construction, and the database summary cap. Tests use real psycopg2 message strings captured from PostgreSQL 15. Well-structured with deterministic stubs.
openmetadata-service/src/main/resources/json/data/testConnections/database/postgres.json Adds "category": "ConnectionGate" to the CheckAccess step. Confirmed valid per the JSON schema enum. Backward-compatible alongside existing shortCircuit: true.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant Runner as TestConnectionRunner
    participant Gate as CheckAccess (ConnectionGate)
    participant TCP as tcp_probe
    participant DB as PostgreSQL
    participant Steps as Remaining 9 Steps

    Runner->>Gate: check_access() → ping(client)
    Gate->>TCP: tcp_probe(host, port)
    alt TCP unreachable
        TCP-->>Gate: NetworkUnreachableError
        Gate-->>Runner: CheckError (NETWORK_ERRORS → "Connection refused")
        Runner->>Steps: skip all (ConnectionNotEstablished)
    else TCP reachable
        TCP-->>Gate: ok
        Gate->>DB: SELECT 1
        alt Auth / DB / pg_hba failure (no SQLSTATE)
            DB-->>Gate: psycopg2 error (message text)
            Gate-->>Runner: CheckError (POSTGRES_ERRORS → title)
            Runner->>Steps: skip all (ConnectionNotEstablished)
        else Access granted
            DB-->>Gate: ok
            Gate-->>Runner: Evidence("connection established")
            Runner->>Steps: run GetDatabases, GetSchemas, GetTables, GetViews, GetTags
            Runner->>Steps: run GetQueries (version probe + pg_stat_statements)
            alt 42P01 (undefined_table)
                Steps-->>Runner: CheckError → "Query history source not found"
            else 42501 (insufficient_privilege)
                Steps-->>Runner: CheckError → "Insufficient privileges"
            end
            Runner->>Steps: run GetColumnMetadata, GetTableComments, GetInformationSchemaColumns
            Steps-->>Runner: Evidence / CheckError
        end
    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 as TestConnectionRunner
    participant Gate as CheckAccess (ConnectionGate)
    participant TCP as tcp_probe
    participant DB as PostgreSQL
    participant Steps as Remaining 9 Steps

    Runner->>Gate: check_access() → ping(client)
    Gate->>TCP: tcp_probe(host, port)
    alt TCP unreachable
        TCP-->>Gate: NetworkUnreachableError
        Gate-->>Runner: CheckError (NETWORK_ERRORS → "Connection refused")
        Runner->>Steps: skip all (ConnectionNotEstablished)
    else TCP reachable
        TCP-->>Gate: ok
        Gate->>DB: SELECT 1
        alt Auth / DB / pg_hba failure (no SQLSTATE)
            DB-->>Gate: psycopg2 error (message text)
            Gate-->>Runner: CheckError (POSTGRES_ERRORS → title)
            Runner->>Steps: skip all (ConnectionNotEstablished)
        else Access granted
            DB-->>Gate: ok
            Gate-->>Runner: Evidence("connection established")
            Runner->>Steps: run GetDatabases, GetSchemas, GetTables, GetViews, GetTags
            Runner->>Steps: run GetQueries (version probe + pg_stat_statements)
            alt 42P01 (undefined_table)
                Steps-->>Runner: CheckError → "Query history source not found"
            else 42501 (insufficient_privilege)
                Steps-->>Runner: CheckError → "Insufficient privileges"
            end
            Runner->>Steps: run GetColumnMetadata, GetTableComments, GetInformationSchemaColumns
            Steps-->>Runner: Evidence / CheckError
        end
    end
Loading

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

IceS2 added 3 commits June 22, 2026 15:32
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.
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.
Move the PostgreSQL connector off the legacy test_connection_steps onto the
new @check / ChecksProvider framework, with structured diagnoses and the shared
TCP reachability preflight.

- PostgresChecks implements all 10 seeded steps (CheckAccess, GetDatabases,
  GetSchemas, GetTables, GetViews, GetTags, GetQueries, GetColumnMetadata,
  GetTableComments, GetInformationSchemaColumns) reusing the shared
  ping/run_sql/list_* helpers - no new shared abstraction.
- POSTGRES_ERRORS maps real psycopg2 failures to diagnoses, validated live
  against PostgreSQL 15: auth (message), database-not-found (message), and
  insufficient-privilege (SQLSTATE 42501). Connect-phase psycopg2 errors carry
  no SQLSTATE, so auth/db-not-found match on message text while query-phase
  privilege errors match on SQLSTATE; NETWORK_ERRORS is composed via .including.
- _get_client registers engine.dispose for deterministic teardown.
- Add GetColumnMetadata/GetTableComments/GetInformationSchemaColumns to the
  shared DatabaseStep enum.
@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Jun 23, 2026
IceS2 and others added 3 commits June 23, 2026 11:53
…diagnosis

Three fixes found while validating the migration against a live PostgreSQL 15
and the running stack:

- postgres.json: CheckAccess now sets category=ConnectionGate. The new runner
  gates on category, not the legacy shortCircuit flag, so without it a failed
  CheckAccess did not short-circuit and every later step opened its own
  connection - turning an unreachable host into a ~9 minute hang instead of a
  ~20s preflight failure. (545s -> 20s, measured.)
- PostgresChecks builds the GetQueries statement lazily inside the check, not at
  construction. get_postgres_time_column_name runs a query; doing it at checks()
  construction connected before the CheckAccess gate, bypassing the preflight.
- POSTGRES_ERRORS: a missing query history source is keyed on SQLSTATE 42P01
  (config-agnostic, queryStatementSource is user-set) -> "Query history source
  not found"; database-not-found matches the quoted connect-phase token so the
  embedded probe SQL referencing pg_database is no longer misread as a missing
  database.
@IceS2
IceS2 marked this pull request as ready for review June 29, 2026 13:46
@IceS2
IceS2 requested a review from a team as a code owner June 29, 2026 13:46
@github-actions

github-actions Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

🔴 Playwright Results — 3 failure(s), 26 flaky

✅ 4508 passed · ❌ 3 failed · 🟡 26 flaky · ⏭️ 55 skipped

Shard Passed Failed Flaky Skipped
🔴 Shard 1 419 2 4 33
🔴 Shard 2 816 1 6 4
🟡 Shard 3 814 0 2 12
🟡 Shard 4 818 0 3 5
✅ Shard 5 831 0 0 0
🟡 Shard 6 810 0 11 1

Genuine Failures (failed on all attempts)

❌ Flow/Tour.spec.ts › Tour should work from help section (shard 1)
TimeoutError: locator.waitFor: Timeout 10000ms exceeded.
Call log:
�[2m  - waiting for locator('[data-tour-elem="badge"]') to be visible�[22m

❌ Pages/Lineage/LineageInteraction.spec.ts › Verify function data in edge drawer (shard 1)
�[31mTest timeout of 180000ms exceeded.�[39m
❌ Features/ContextCenterPermission.spec.ts › Data Steward can edit content, title, owners, tags, and glossary terms but cannot add article, domain, reviewer, data product, or data assets (shard 2)
Error: �[2mexpect(�[22m�[31mlocator�[39m�[2m).�[22mtoBeVisible�[2m(�[22m�[2m)�[22m failed

Locator: getByTestId('tags-container').getByTestId('add-tag')
Expected: visible
Timeout: 15000ms
Error: element(s) not found

Call log:
�[2m  - Expect "toBeVisible" with timeout 15000ms�[22m
�[2m  - waiting for getByTestId('tags-container').getByTestId('add-tag')�[22m

🟡 26 flaky test(s) (passed on retry)
  • Features/Glossary/GlossaryPagination.spec.ts › should filter by InReview status (shard 1, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab IS visible for supported type: mlmodel (shard 1, 1 retry)
  • Flow/SearchRBAC.spec.ts › User without permission (shard 1, 1 retry)
  • Flow/SearchRBAC.spec.ts › a fully denied user sees neither asset type when browsing (shard 1, 2 retries)
  • Features/ContextCenterArticles.spec.ts › Article listing search filters, clears, and shows empty state (shard 2, 2 retries)
  • Features/ContextCenterArticles.spec.ts › Article list cards, recently viewed widget, and pagination work (shard 2, 1 retry)
  • Features/ContextCenterMemories.spec.ts › clicking a memory row adds ?memory= param to the URL (shard 2, 1 retry)
  • Features/ContextCenterMemories.spec.ts › adding a linked asset in edit mode shows entity badge on the row (shard 2, 1 retry)
  • Features/ContextCenterMemories.spec.ts › typing the linked table name in the asset search returns it as a result (shard 2, 1 retry)
  • Features/ContextCenterPermission.spec.ts › user with deleteAll permission can see delete action but not restore action on an archived document, and can delete it (shard 2, 1 retry)
  • Features/SearchExport.spec.ts › Export queues a background job and downloads from the jobs tray (shard 3, 1 retry)
  • Features/Table.spec.ts › should persist page size (shard 3, 1 retry)
  • Flow/ConnectionConfigLayout.spec.ts › should clear inactive Snowflake auth fields before test connection and unlock ingestion filters (shard 4, 1 retry)
  • Flow/ExploreDiscovery.spec.ts › Should display domain and owner of deleted asset in suggestions when showDeleted is on (shard 4, 1 retry)
  • Pages/DataContracts.spec.ts › Create Data Contract and validate for ApiEndpoint (shard 4, 1 retry)
  • Pages/ExplorePageRightPanel.spec.ts › Should allow Data Steward to edit tier for dashboardDataModel (shard 6, 1 retry)
  • Pages/GlossaryImportExport.spec.ts › Import partial success - some terms pass, some fail (shard 6, 1 retry)
  • Pages/GlossaryImportExport.spec.ts › Glossary CSV import rejects unknown relation type (shard 6, 1 retry)
  • Pages/Lineage/DataAssetLineage.spec.ts › Column lineage for searchIndex -> container (shard 6, 1 retry)
  • Pages/Lineage/DataAssetLineage.spec.ts › Column lineage for mlModel -> dashboardDataModel (shard 6, 1 retry)
  • Pages/Lineage/LineageFilters.spec.ts › Verify lineage schema filter selection (shard 6, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab is NOT visible for pipelineService in platform lineage (shard 6, 1 retry)
  • Pages/TagPageRightPanel.spec.ts › Should open right panel when clicking asset in tag assets page (shard 6, 1 retry)
  • Pages/TasksUIFlow.spec.ts › Create and reject tag task for Topic via UI (shard 6, 1 retry)
  • Pages/TestSuite.spec.ts › Logical TestSuite (shard 6, 1 retry)
  • Pages/UserDetails.spec.ts › Create team with domain and verify visibility of inherited domain in user profile after team removal (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

…TATE guard

- test: replace real-socket port probe with a tcp_probe stub - removes the
  ephemeral-port TOCTOU and the 20s macOS connect-timeout; still asserts the
  check_access -> ping -> _preflight wiring and refused classification
- _pgcode: use explicit `is not None` so an empty-string SQLSTATE is not
  silently discarded
@gitar-bot

gitar-bot Bot commented Jun 30, 2026

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

Migrates PostgreSQL connection testing to the @check framework with structured error classification and improved gate logic. Resolves performance issues and test flakiness while ensuring proper short-circuiting on connection failure.

✅ 3 resolved
✅ Bug: Eager query in checks() bypasses preflight and step timeout

📄 ingestion/src/metadata/ingestion/source/database/postgres/connection.py:182-192 📄 ingestion/src/metadata/ingestion/source/database/postgres/connection.py:155-157
PostgresConnection.checks() calls self._test_queries_statement(), which calls get_postgres_time_column_name(engine=self.client). That helper eagerly opens a real connection and runs a query against the server. This happens in BaseConnection.test_connection before the TestConnectionRunner runs any @check, so it executes outside the per-step STEP_TIMEOUT_SECONDS budget and outside the new TCP reachability preflight.

Consequences:

  • For an unreachable host, the driver's own connect (whose default timeout can be minutes) runs here first, blocking test_connection before CheckAccess ever runs — defeating the whole point of the preflight, which was added to fail fast with a network-vs-auth diagnosis.
  • get_postgres_time_column_name swallows the exception and falls back, so the failure is silent, but the latency/hang is real and the structured diagnosis is lost.

Fix: compute the queries statement lazily inside the GetQueries check (or pass a callable to PostgresChecks and resolve it inside get_queries), so the server round-trip happens within a timed/diagnosed step rather than during provider construction.

✅ Edge Case: ping() TCP preflight may spuriously fail SSH-tunneled connections

📄 ingestion/src/metadata/core/connections/test_connection/checks/database.py:137-151 📄 ingestion/src/metadata/ingestion/source/database/postgres/connection.py:131-133
The TCP reachability preflight added to the shared ping() connects directly to client.url.host:client.url.port. For connectors reached through an SSH tunnel or a proxy where the engine URL still carries the original (directly-unreachable) remote host:port, the preflight will raise a spurious NetworkUnreachableError/'Connection timed out' even though the real driver connection would have succeeded through the tunnel.

The ping docstring acknowledges this and advises such connectors to call run_sql directly, but both Postgres and MySQL check_access use ping, and their service configs support sshTunnel. If/when tunneling is wired into this new framework, CheckAccess will mis-report tunneled hosts as network failures. Worth gating the preflight (e.g. skip when a tunnel/proxy transport is configured) or documenting the gap explicitly as unsupported.

✅ Quality: Ephemeral-port reuse can make unreachable-host test flaky

📄 ingestion/tests/unit/source/database/postgres/test_connection.py:207-219
In test_check_access_reports_unreachable_host_as_network_failure the test binds a socket to port 0, reads the assigned ephemeral port, closes the socket, then expects tcp_probe to get a connection refused at that port. There is a small race window: between closing the socket and the preflight connecting, another process (or the OS) could bind that ephemeral port, in which case the connection would succeed and the test would fail intermittently with no real defect. This is a known idiom but inherently racy.

Consider making the assertion more robust, e.g. pick a port that is very unlikely to be bound / in the reserved range, retry on unexpected success, or assert only that a NetworkUnreachableError is raised when the probe target is closed by binding-and-immediately-probing without the close/reopen gap. The production code itself is fine; this is purely about test stability in CI.

Options

Display: compact → Showing less information.

Comment with these commands to change:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

Copilot AI review requested due to automatic review settings July 3, 2026 13:40

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 4 out of 4 changed files in this pull request and generated no new comments.

…ses sample cap

- POSTGRES_ERRORS: match `role "x" does not exist` (trust/peer connect-phase, no
  SQLSTATE) as Authentication failed, guarded on the `role "` token so it does not
  collide with the `database "` not-found matcher
- GetDatabases summary reports "N+" when the row count hits run_sql's
  DEFAULT_SAMPLE_ROWS cap, instead of implying an exact enumeration
`list` was narrower than run_sql's `Callable[[Sequence[Row]], str]`, tripping
reportArgumentType. The summarizer only needs `len(rows)`, so `Sequence[object]`
is the honest contract and satisfies run_sql contravariantly.
Copilot AI review requested due to automatic review settings July 3, 2026 21:23

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 4 out of 4 changed files in this pull request and generated no new comments.

…nnection-framework

# Conflicts:
#	ingestion/src/metadata/core/connections/test_connection/checks/database.py

@Khairajani Khairajani 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.

LGTM

@Khairajani Khairajani 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.

Looks solid — really like that the tests use real captured psycopg2 messages. One small note inline.

# psycopg2 surfaces on ``.pgcode``. Bad host / port raise before the driver and are
# caught by the TCP preflight in ``ping`` via NETWORK_ERRORS.
POSTGRES_ERRORS = ErrorPack(
when(Matchers.contains("password authentication failed")).diagnose(

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.

Small note: these connect-time errors are matched on the English message text, so a Postgres server running in another language (localized lc_messages) wouldn't match and the user would just see the raw error. Not a blocker — the SQLSTATE ones below are language-proof — just flagging.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I saw that as well but I think we should defer this

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 4 out of 4 changed files in this pull request and generated 1 comment.

@sonarqubecloud

sonarqubecloud Bot commented Jul 7, 2026

Copy link
Copy Markdown

@gitar-bot

gitar-bot Bot commented Jul 8, 2026

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

Migrates PostgreSQL connection testing to the @check framework, enabling structured error diagnostics and a proper ConnectionGate to prevent long-running timeouts. All legacy steps are preserved with improved lazy-loading and verified error handling.

✅ 3 resolved
✅ Bug: Eager query in checks() bypasses preflight and step timeout

📄 ingestion/src/metadata/ingestion/source/database/postgres/connection.py:182-192 📄 ingestion/src/metadata/ingestion/source/database/postgres/connection.py:155-157
PostgresConnection.checks() calls self._test_queries_statement(), which calls get_postgres_time_column_name(engine=self.client). That helper eagerly opens a real connection and runs a query against the server. This happens in BaseConnection.test_connection before the TestConnectionRunner runs any @check, so it executes outside the per-step STEP_TIMEOUT_SECONDS budget and outside the new TCP reachability preflight.

Consequences:

  • For an unreachable host, the driver's own connect (whose default timeout can be minutes) runs here first, blocking test_connection before CheckAccess ever runs — defeating the whole point of the preflight, which was added to fail fast with a network-vs-auth diagnosis.
  • get_postgres_time_column_name swallows the exception and falls back, so the failure is silent, but the latency/hang is real and the structured diagnosis is lost.

Fix: compute the queries statement lazily inside the GetQueries check (or pass a callable to PostgresChecks and resolve it inside get_queries), so the server round-trip happens within a timed/diagnosed step rather than during provider construction.

✅ Edge Case: ping() TCP preflight may spuriously fail SSH-tunneled connections

📄 ingestion/src/metadata/core/connections/test_connection/checks/database.py:137-151 📄 ingestion/src/metadata/ingestion/source/database/postgres/connection.py:131-133
The TCP reachability preflight added to the shared ping() connects directly to client.url.host:client.url.port. For connectors reached through an SSH tunnel or a proxy where the engine URL still carries the original (directly-unreachable) remote host:port, the preflight will raise a spurious NetworkUnreachableError/'Connection timed out' even though the real driver connection would have succeeded through the tunnel.

The ping docstring acknowledges this and advises such connectors to call run_sql directly, but both Postgres and MySQL check_access use ping, and their service configs support sshTunnel. If/when tunneling is wired into this new framework, CheckAccess will mis-report tunneled hosts as network failures. Worth gating the preflight (e.g. skip when a tunnel/proxy transport is configured) or documenting the gap explicitly as unsupported.

✅ Quality: Ephemeral-port reuse can make unreachable-host test flaky

📄 ingestion/tests/unit/source/database/postgres/test_connection.py:207-219
In test_check_access_reports_unreachable_host_as_network_failure the test binds a socket to port 0, reads the assigned ephemeral port, closes the socket, then expects tcp_probe to get a connection refused at that port. There is a small race window: between closing the socket and the preflight connecting, another process (or the OS) could bind that ephemeral port, in which case the connection would succeed and the test would fail intermittently with no real defect. This is a known idiom but inherently racy.

Consider making the assertion more robust, e.g. pick a port that is very unlikely to be bound / in the reserved range, retry on unexpected success, or assert only that a NetworkUnreachableError is raised when the probe target is closed by binding-and-immediately-probing without the close/reopen gap. The production code itself is fine; this is purely about test stability in CI.

Options

Display: compact → Showing less information.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

This branch was previously deployed

1 inactive deployment
test — fdfc1c23 Deployed Jul 7, 2026 by IceS2 via playwright-ci-postgresql (3, 6) #55155
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.

Migrate Postgres connector to the new TestConnection framework

5 participants