Repository navigation
Fixes #29341: migrate Postgres test connection to the @check framework - #29342
Conversation
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.
…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.
🔴 Playwright Results — 3 failure(s), 26 flaky✅ 4508 passed · ❌ 3 failed · 🟡 26 flaky · ⏭️ 55 skipped
Genuine Failures (failed on all attempts)❌
|
…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
Code Review ✅ Approved 3 resolved / 3 findingsMigrates PostgreSQL connection testing to the ✅ 3 resolved✅ Bug: Eager query in checks() bypasses preflight and step timeout
✅ Edge Case: ping() TCP preflight may spuriously fail SSH-tunneled connections
✅ Quality: Ephemeral-port reuse can make unreachable-host test flaky
OptionsDisplay: compact → Showing less information. Comment with these commands to change:
Was this helpful? React with 👍 / 👎 | Gitar |
…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.
…nnection-framework # Conflicts: # ingestion/src/metadata/core/connections/test_connection/checks/database.py
Khairajani
left a comment
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I saw that as well but I think we should defer this
|
Code Review ✅ Approved 3 resolved / 3 findingsMigrates PostgreSQL connection testing to the ✅ 3 resolved✅ Bug: Eager query in checks() bypasses preflight and step timeout
✅ Edge Case: ping() TCP preflight may spuriously fail SSH-tunneled connections
✅ Quality: Ephemeral-port reuse can make unreachable-host test flaky
OptionsDisplay: compact → Showing less information. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Gitar |



Fixes #29341
What
Migrates PostgreSQL's test connection from the legacy
test_connection_stepsto the new@check/ChecksProviderframework (the path MySQL uses) — structured per-step diagnoses plus the shared TCP preflight that separates a network failure from an auth failure.How
PostgresChecksimplements all 10 seeded steps as@checkmethods, reusing the sharedping/run_sql/list_*helpers. No new shared abstraction — earned only when a second connector reuses one.POSTGRES_ERRORS, validated live against PostgreSQL 15:database "…")4250142P01pg_hba.confentry.including(NETWORK_ERRORS))postgres.json:CheckAccessnowcategory: ConnectionGate. The new runner gates oncategory, not the legacyshortCircuitflag — 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
42P01so it holds for anyqueryStatementSource, not justpg_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_clientregistersengine.dispose. AddsGetColumnMetadata/GetTableComments/GetInformationSchemaColumnsto the sharedDatabaseStepenum.Greptile Summary
This PR migrates PostgreSQL's test-connection implementation from the legacy
test_connection_db_commonpath to the new@check/ChecksProviderframework, aligning it with the pattern already used by MySQL. The key behavioral improvement is a TCP preflight inCheckAccessthat separates network failures from auth/database failures in under 20s instead of waiting ~9 minutes per step.PostgresChecksimplements all 10 steps as@checkmethods. 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 sharedNETWORK_ERRORSappended via.including().postgres.jsonadds"category": "ConnectionGate"toCheckAccess(alongside the legacyshortCircuit: true) so the new runner can gate onCategory.ConnectionGatewithout breaking older runners.get_postgres_time_column_nameis invoked insideget_queries()(not atPostgresChecks.__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 Noneguards. 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
is Noneguards. Engine disposal registered via _on_close. No issues found.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%%{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 endReviews (12): Last reviewed commit: "Merge branch 'main' into feat/postgres-t..." | Re-trigger Greptile