From 3d4bb56f4a5f2599bdead0b692abfb42e67e8e7a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 15:41:29 -0800 Subject: [PATCH 1/7] fix(sources): the default PostgreSQL source id names the server (ITL-1267) The default source id of a PostgreSQLTableSource is now postgresql_table::/.., with the host and port libpq reports for the live connection (PQhost, PQport): a host name lower-cased, an IPv6 address bracketed in its exploded form (no '::'), a socket directory as given, the port always the number used. One database, schema and table name on two servers now gives two ids. Connection parameters that name several servers (DSN, PGHOST/PGHOSTADDR or a service file) give no default: the server reached can change between connections. A '/' in a database, schema or table name gives no default. No user name, password or other parameter enters the id. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 5 +- CLAUDE.md | 5 +- changelog.d/ITL-1267.md | 15 ++ docs/concepts/sources.md | 11 +- docs/reference/hashing.md | 20 +- .../core/sources/postgresql_table_source.py | 96 ++++++++- src/orcapod/databases/postgresql_connector.py | 47 +++- .../sources/test_postgresql_table_source.py | 203 +++++++++++++++++- ...est_postgresql_table_source_integration.py | 187 ++++++++++++++++ .../sources/test_source_check_for_new_data.py | 6 +- .../test_postgresql_connector.py | 119 ++++++++++ 11 files changed, 686 insertions(+), 28 deletions(-) create mode 100644 changelog.d/ITL-1267.md diff --git a/.zed/rules b/.zed/rules index e9a83842d..5d3c141e0 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1076,7 +1076,10 @@ data. The rules: only by core/sources/source_ids.hash_source_id; one built from where the data lives is :, built only by location_source_id: csv:, delta_table:, sqlite_table::main.
, - postgresql_table:..
, + postgresql_table::/..
(the server the connection + reached, as libpq reports it: a host name lower-cased, an IPv6 address bracketed and + exploded, a socket directory as given, the port always a number; a DSN naming several + servers has no default; developer, November 18, 2026, ITL-1267), spiraldb_table:..
@
(developer, November 16, 2026); a location whose parts hold their separator has no default (source_ids.joined_location). A DBTableSource used directly (a generic connector, no database address) has no default: diff --git a/CLAUDE.md b/CLAUDE.md index c55f8bd61..0507c8b16 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1118,7 +1118,10 @@ data. The rules: only by `core/sources/source_ids.hash_source_id`; one built from where the data lives is `:`, built only by `location_source_id`: `csv:`, `delta_table:`, `sqlite_table::main.
`, - `postgresql_table:..
`, + `postgresql_table::/..
` (the server the connection + reached, as libpq reports it: a host name lower-cased, an IPv6 address bracketed and + exploded, a socket directory as given, the port always a number; a DSN naming several + servers has no default; developer, November 18, 2026, ITL-1267), `spiraldb_table:..
@
` (developer, November 16, 2026); a location whose parts hold their separator has no default (`source_ids.joined_location`). A `DBTableSource` used directly (a generic connector, no database address) has no default: diff --git a/changelog.d/ITL-1267.md b/changelog.d/ITL-1267.md new file mode 100644 index 000000000..403999c47 --- /dev/null +++ b/changelog.d/ITL-1267.md @@ -0,0 +1,15 @@ +### Breaking changes and migration + +- The default source id of a `PostgreSQLTableSource` names the server the connection reached + (ITL-1267): `postgresql_table::/..
` (was + `postgresql_table:..
`), so one database, schema and table name on + two servers gives two ids. The host is the name or address as libpq reports it, a host name + in lower case, an IPv6 address in brackets in its exploded form (no `::`), a Unix-domain + socket directory as given; the port is always the number used, the default `5432` included. + No user name, password or other connection parameter enters the id. The system-tag values + and source-info tokens of rows read from PostgreSQL without a `source_id` change with it; a + `source_id` you give is used as before, and a saved job keeps the id it was saved with. +- A PostgreSQL source whose DSN, `PGHOST` / `PGHOSTADDR` setting or service file names several + servers (`host=a,b`) has no default source id and raises `ValueError` unless it is given a + `source_id`: the server reached can change from one connection to the next. A database, + schema or table name holding `/` has no default either, as one holding `.` already had. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index a695bd1b4..323c22d47 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -36,9 +36,14 @@ hashing) and produces the final immutable stream. `orcapod.sources` also provides database-backed sources (`SQLiteTableSource`, `PostgreSQLTableSource`, `SpiralDBTableSource`) and `PollingSource` for data that arrives over time; see the [API reference](../api/sources.md). Their default `source_id` names the table -where it lives (`sqlite_table::main.
`). `DBTableSource`, the base they share, -can also be used directly over any connector; a connector gives no address of its database, -so it then has no default and needs a `source_id`. +where it lives (`sqlite_table::main.
`, +`postgresql_table::/..
`, with the server the connection +reached; the +[hashing reference](../reference/hashing.md#default-source-ids-and-row-identifiers) has +every form). A PostgreSQL DSN that names several servers (`host=a,b`) has no default: give +such a source a `source_id`. `DBTableSource`, the base they share, can also be used directly +over any connector; a connector gives no address of its database, so it then has no default +and needs a `source_id`. Two construction rules apply to every source and are the most common first errors: diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 02a5059a0..1da12d9fa 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -170,7 +170,7 @@ category, but we should make it totally overridable"; November 16, 2026, ITL-115 | `CSVSource` | `csv` | `csv:` | | `DeltaTableSource` | `delta_table` | `delta_table:` | | `SQLiteTableSource` | `sqlite_table` | `sqlite_table::main.
` (SQLite names a table `.
`; the main database's schema is `main`) | -| `PostgreSQLTableSource` | `postgresql_table` | `postgresql_table:..
` (the three-part name, from `current_database()` and `current_schema()`) | +| `PostgreSQLTableSource` | `postgresql_table` | `postgresql_table::/..
` (the server the connection reached, then the three-part name, from `current_database()` and `current_schema()`; see below) | | `DBTableSource` (any other connector) | `db_table` | none: `source_id` is required. The connector protocol exposes no database address, and the table name alone does not say which database the table is in (developer decision, November 16, 2026) | | `SpiralDBTableSource` | `spiraldb_table` | `spiraldb_table:..
@
` (Spiral's own table identifier, then SpiralDB's table id; `SPIRALDB_SOURCE_ID_HAS_TABLE_ID`) | | `PollingSource` | `polling_source` | `polling_source:semantic_v1:` of `impl.identity()` (never its `repr`) | @@ -181,8 +181,22 @@ A location default names the data where it lives, so two sources of one kind sha when they read the same data. The generic `DBTableSource` knows no database, so it has no default and refuses to be built without a `source_id`. A location whose parts cannot be told apart has no default (`joined_location`): a SQLite table name holding `:`, a PostgreSQL or -SpiralDB name holding `.`, a SpiralDB address or table id holding `@`. Such a source needs a -`source_id`. +SpiralDB name holding `.`, a PostgreSQL name holding `/`, a SpiralDB address or table id +holding `@`. Such a source needs a `source_id`. + +A PostgreSQL default names the server the connection reached (developer, November 18, 2026, +ITL-1267), as libpq reports it, so one database, schema and table name on two servers gives +two ids. The host is the name or address as given (with `host` and `hostaddr` both given, +the host), or the directory of a Unix-domain socket; never the address a name resolved to. +A host name is written in lower case (`DB.Example.ORG` and `db.example.org` are one id); an +IPv6 address in brackets and in its exploded form, which holds no `::` +(`[0000:0000:0000:0000:0000:0000:0000:0001]` for `::1`); an IPv4 address and a socket +directory as given. The port is always the number used, the default `5432` included, so a +DSN with `port=5432` and one without it give one id. Two spellings of one server are two +ids (`localhost` and `127.0.0.1`), as two spellings of one CSV path are. A DSN, a `PGHOST` +or `PGHOSTADDR` setting or a service file that names several servers (`host=a,b`) gives no +default: the server reached can change from one connection to the next. No user name, +password or other connection parameter enters the id. A row's record id is its row identifier (site 5), chosen by `record_id_columns` (a column name or several, in key order; every source accepts it): diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 892f227ae..d440094ef 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -12,6 +12,7 @@ from __future__ import annotations +import ipaddress from collections.abc import Collection, Iterator from contextlib import contextmanager from typing import TYPE_CHECKING, Any, ClassVar, cast @@ -30,6 +31,68 @@ from orcapod.config import OrcapodConfig +def _server_name(host: str) -> str: + """Return the host as it is written in a default source id. + + A host name is lower-cased (DNS names are case-insensitive); an IPv6 address is + bracketed, as in a URI, in its exploded form, so it never holds ``::`` and has one + spelling (a zone, ``%eth0``, is kept as given); an IPv4 address and a socket path + (``/...``, or ``@...`` for a Linux abstract socket) are kept as given. + + Args: + host: The host the connection reports (``PQhost``). + + Returns: + The host's name in the id. + """ + address, zone_mark, zone = host.partition("%") + try: + ip = ipaddress.ip_address(address) + except ValueError: + ip = None + if isinstance(ip, ipaddress.IPv6Address): + return f"[{ip.exploded}{zone_mark}{zone}]" + if ip is not None or host.startswith(("/", "@")): + return host + return host.lower() + + +def postgresql_table_address( + host: str, port: int, database: str, schema: str, table: str +) -> str: + """Return ``:/..
``, a PostgreSQL table's address. + + The location of the default source id (``postgresql_table:
``, ITL-1267): + the server the connection reached, then the table's three-part name. The host is + written by ``_server_name``; the port is always the number. The address names one + table only: the parts of the three-part name hold neither ``.`` nor ``/``, so the + last ``/`` ends the server and the last ``:`` before it ends the host. + + Args: + host: The host the connection reports: a host name, an IP address or a + socket directory. + port: The port the connection used. + database: The connection's ``current_database()``. + schema: The connection's ``current_schema()``. + table: The table's name. + + Returns: + The table's address. + + Raises: + ValueError: If the host is empty, or the database, schema or table name is + empty or holds ``.`` or ``/``; give the source a ``source_id``. + """ + if not host: + raise ValueError( + "the PostgreSQL connection reports no host, so the table has no default " + "source id; give the source a source_id" + ) + joined_location("/", database, schema, table) + name = joined_location(".", database, schema, table) + return f"{_server_name(host)}:{port}/{name}" + + class PostgreSQLTableSource(DBTableSource): """A read-only Source backed by a table in a PostgreSQL database. @@ -59,7 +122,9 @@ class PostgreSQLTableSource(DBTableSource): record_id_columns: The key columns that identify a row; ``None``: the primary key (a table without one is refused); ``()``: the position. source_id: Canonical source name. Defaults to - ``postgresql_table:..
``. + ``postgresql_table::/..
`` + (``postgresql_table_address``); a DSN that names several servers has + no default. label: Human-readable label for this source node. data_context: Data context governing type conversion and hashing. config: OrcaPod configuration. @@ -115,12 +180,13 @@ def __init__( @override def _table_address(self, connector: DBConnectorProtocol, table_name: str) -> str: - """Return ``..
``, the table's three-part name. + """Return ``:/..
``, the table's address. - The SQL standard's catalog.schema.table, which PostgreSQL documents as - ``database.schema.table``; the database and schema are the connection's - ``current_database()`` and ``current_schema()``, where the connector finds - the table (ITL-1154). + The server the connection reached (host and port as libpq reports them), + then the table's three-part name, ``database.schema.table``, from the + connection's ``current_database()`` and ``current_schema()``, where the + connector finds the table (ITL-1154, ITL-1267). Built by + ``postgresql_table_address``. Args: connector: The connector the source reads through. @@ -128,9 +194,23 @@ def _table_address(self, connector: DBConnectorProtocol, table_name: str) -> str Returns: The table's address. + + Raises: + ValueError: If the connection parameters name several servers: the one + reached can change from one connection to the next, so it is no + name for the table. """ - database, schema = cast("PostgreSQLConnector", connector).current_location() - return joined_location(".", database, schema, table_name) + pg = cast("PostgreSQLConnector", connector) + if pg.names_several_servers(): + raise ValueError( + f"the connection parameters of the PostgreSQL source over table " + f"{table_name!r} (its DSN, PGHOST or PGHOSTADDR, or a service file) " + "name several servers, and the one reached can change from one " + "connection to the next, so the table has no default source id; give " + "the source a source_id" + ) + host, port, database, schema = pg.current_location() + return postgresql_table_address(host, port, database, schema, table_name) @contextmanager @override diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 39be7f6d2..5151b80d5 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -15,6 +15,7 @@ import itertools import logging +import os import re import threading import uuid @@ -403,23 +404,57 @@ def get_table_names(self) -> list[str]: ) return [row[0] for row in cur.fetchall()] - def current_location(self) -> tuple[str, str]: - """Return ``(current_database(), current_schema())`` of the connection. + def current_location(self) -> tuple[str, int, str, str]: + """Return the server, database and schema the connection reached. - Where the connector finds its tables: the first two parts of a table's - three-part name, ``database.schema.table``. + ``(host, port, current_database(), current_schema())``: where the connector + finds its tables. The host and port are what libpq reports for the live + connection (``PQhost``, ``PQport``): the host name or IP address as given + (with ``host`` and ``hostaddr`` both given, the host), or the directory of a + Unix-domain socket; the port is the one used, the compiled default when none + was given. Never the resolved address, the user, the password or any other + connection parameter (ITL-1267). Returns: - The database and schema names. + The host, the port, the database and the schema. + + Raises: + ValueError: If the connection has no current schema. """ with self._lock: conn = self._require_open() + host, port = conn.info.host, conn.info.port with conn.cursor() as cur: cur.execute("SELECT current_database(), current_schema()") row = cur.fetchone() if row is None or row[0] is None or row[1] is None: raise ValueError("the PostgreSQL connection has no current schema") - return str(row[0]), str(row[1]) + return str(host), int(port), str(row[0]), str(row[1]) + + def names_several_servers(self) -> bool: + """Return whether the connection parameters name more than one server. + + libpq accepts a comma-separated list of hosts (``host=a,b``, or + ``postgresql://a:5432,b:5433/db``) and connects to the first that answers. + The list may come from the DSN, from ``PGHOST`` / ``PGHOSTADDR`` when the DSN + names no host, or from a service file; the first two are read from the DSN + and the environment, a service file from the parameters the connection + reports (psycopg tries the hosts of the DSN and the environment one by one, + so its connection reports only the one it reached). + + Returns: + ``True`` when ``host`` or ``hostaddr`` holds more than one entry. + """ + from psycopg.conninfo import conninfo_to_dict + + given = conninfo_to_dict(self._dsn) + with self._lock: + reported = self._require_open().info.get_parameters() + for key, envvar in (("host", "PGHOST"), ("hostaddr", "PGHOSTADDR")): + value = given[key] if key in given else os.environ.get(envvar) + if "," in str(value or "") or "," in reported.get(key, ""): + return True + return False def get_pk_columns(self, table_name: str) -> list[str]: """Return primary-key column names in key-sequence order.""" diff --git a/tests/test_core/sources/test_postgresql_table_source.py b/tests/test_core/sources/test_postgresql_table_source.py index e2f79270d..61c2d60d2 100644 --- a/tests/test_core/sources/test_postgresql_table_source.py +++ b/tests/test_core/sources/test_postgresql_table_source.py @@ -73,7 +73,8 @@ def _make_mock_connector( mock.get_table_names.return_value = table_names mock.get_pk_columns.return_value = pk_columns - mock.current_location.return_value = ("orcapod", "public") + mock.current_location.return_value = ("localhost", 5432, "orcapod", "public") + mock.names_several_servers.return_value = False mock.get_column_info.return_value = [] mock.iter_batches.return_value = iter(batches) return mock @@ -176,13 +177,16 @@ def test_composite_pk_all_columns_are_tags(self): assert "user_id" in tag_schema assert "event_id" in tag_schema - def test_default_source_id_is_table_name(self): + def test_default_source_id_names_server_and_table(self): from orcapod.core.sources import PostgreSQLTableSource with patch(_PATCH) as mock_cls: mock_cls.return_value = _make_mock_connector() src = PostgreSQLTableSource(DSN, "measurements", tag_only_columns=True) - assert src.source_id == "postgresql_table:orcapod.public.measurements" + assert ( + src.source_id + == "postgresql_table:localhost:5432/orcapod.public.measurements" + ) def test_explicit_source_id_overrides_default(self): from orcapod.core.sources import PostgreSQLTableSource @@ -444,7 +448,7 @@ def test_has_tag_columns(self): def test_has_source_id(self): assert ( self._make_src().to_config()["source_id"] - == "postgresql_table:orcapod.public.measurements" + == "postgresql_table:localhost:5432/orcapod.public.measurements" ) def test_has_content_hash(self): @@ -536,3 +540,194 @@ def test_resolve_source_from_config_dispatches_to_postgresql_table_source(): src2 = resolve_source_from_config(config) assert isinstance(src2, PostgreSQLTableSource) + + +# =========================================================================== +# 12. The default source id names the server (ITL-1267) +# =========================================================================== + + +def _server_connector( + host: str, + port: int, + database: str = "orcapod", + schema: str = "public", + *, + several_servers: bool = False, +) -> MagicMock: + """A mocked connector whose connection reports ``host``, ``port`` and location.""" + mock = _make_mock_connector() + mock.current_location.return_value = (host, port, database, schema) + mock.names_several_servers.return_value = several_servers + return mock + + +class TestTableAddress: + """``postgresql_table_address``: the location of the default source id.""" + + @pytest.mark.parametrize( + ("host", "port", "expected"), + [ + ("db.example.org", 5432, "db.example.org:5432/orcapod.public.t"), + ("db.example.org", 5433, "db.example.org:5433/orcapod.public.t"), + # A DNS name is case-insensitive: one spelling. + ("DB.Example.ORG", 5432, "db.example.org:5432/orcapod.public.t"), + ("LOCALHOST", 5432, "localhost:5432/orcapod.public.t"), + # An IPv4 address as reported. + ("127.0.0.1", 5432, "127.0.0.1:5432/orcapod.public.t"), + # An IPv6 address: bracketed, in the exploded form (never '::'). + ( + "::1", + 5432, + "[0000:0000:0000:0000:0000:0000:0000:0001]:5432/orcapod.public.t", + ), + ( + "2001:DB8::1", + 5432, + "[2001:0db8:0000:0000:0000:0000:0000:0001]:5432/orcapod.public.t", + ), + ( + "2001:db8:0:0:0:0:0:1", + 5432, + "[2001:0db8:0000:0000:0000:0000:0000:0001]:5432/orcapod.public.t", + ), + ( + "fe80::1%eth0", + 5432, + "[fe80:0000:0000:0000:0000:0000:0000:0001%eth0]:5432/orcapod.public.t", + ), + # A Unix-domain socket directory, as reported, case kept. + ( + "/var/run/postgresql", + 5432, + "/var/run/postgresql:5432/orcapod.public.t", + ), + ("/Tmp/PG", 5433, "/Tmp/PG:5433/orcapod.public.t"), + # A Linux abstract-namespace socket, as reported. + ("@pgsock", 5432, "@pgsock:5432/orcapod.public.t"), + ], + ) + def test_address(self, host: str, port: int, expected: str) -> None: + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + assert postgresql_table_address(host, port, "orcapod", "public", "t") == ( + expected + ) + + def test_spellings_of_one_ipv6_address_give_one_address(self) -> None: + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + addresses = { + postgresql_table_address(host, 5432, "d", "s", "t") + for host in ("::1", "0::1", "0:0:0:0:0:0:0:1") + } + assert len(addresses) == 1 + + @pytest.mark.parametrize( + ("database", "schema", "table"), + [ + ("a/b", "public", "t"), + ("orcapod", "a/b", "t"), + ("orcapod", "public", "a/b"), + ("a.b", "public", "t"), + ("orcapod", "a.b", "t"), + ("orcapod", "public", "a.b"), + ], + ) + def test_separator_in_a_name_has_no_address( + self, database: str, schema: str, table: str + ) -> None: + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + with pytest.raises(ValueError, match="source_id"): + postgresql_table_address("localhost", 5432, database, schema, table) + + def test_empty_host_has_no_address(self) -> None: + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + with pytest.raises(ValueError, match="source_id"): + postgresql_table_address("", 5432, "orcapod", "public", "t") + + +class TestDefaultSourceIdNamesServer: + def _source( + self, connector: MagicMock, dsn: str = DSN, source_id: str | None = None + ): + from orcapod.core.sources import PostgreSQLTableSource + + with patch(_PATCH) as mock_cls: + mock_cls.return_value = connector + return PostgreSQLTableSource( + dsn, "measurements", source_id=source_id, tag_only_columns=True + ) + + def test_one_table_name_on_several_servers_gives_several_ids(self) -> None: + servers = [ + ("db.example.org", 5432), + ("db.example.org", 5433), + ("db2.example.org", 5432), + ("/var/run/postgresql", 5432), + ] + ids = [self._source(_server_connector(h, p)).source_id for h, p in servers] + assert ids == [ + "postgresql_table:db.example.org:5432/orcapod.public.measurements", + "postgresql_table:db.example.org:5433/orcapod.public.measurements", + "postgresql_table:db2.example.org:5432/orcapod.public.measurements", + "postgresql_table:/var/run/postgresql:5432/orcapod.public.measurements", + ] + # In the reverse order each source keeps its own id. + reversed_ids = [ + self._source(_server_connector(h, p)).source_id + for h, p in reversed(servers) + ] + assert reversed_ids == list(reversed(ids)) + + def test_one_server_gives_one_id_whatever_the_dsn(self) -> None: + dsns = [ + "postgresql://alice:s3cret@db.example.org:5432/orcapod", + "host=db.example.org port=5432 dbname=orcapod user=alice password=s3cret", + "host=DB.EXAMPLE.ORG dbname=orcapod user=bob", + ] + ids = { + self._source(_server_connector("db.example.org", 5432), dsn).source_id + for dsn in dsns + } + assert ids == { + "postgresql_table:db.example.org:5432/orcapod.public.measurements" + } + + @pytest.mark.parametrize( + "dsn", + [ + "postgresql://alice:s3cret@db.example.org:5432/orcapod", + "host=db.example.org port=5432 dbname=orcapod user=alice password=s3cret", + ], + ) + def test_id_never_holds_user_or_password(self, dsn: str) -> None: + source_id = self._source( + _server_connector("db.example.org", 5432), dsn + ).source_id + assert "alice" not in source_id + assert "s3cret" not in source_id + + def test_several_servers_have_no_default(self) -> None: + connector = _server_connector("db.example.org", 5432, several_servers=True) + with pytest.raises(ValueError, match="several servers.*source_id"): + self._source(connector) + + def test_given_source_id_is_used_as_given(self) -> None: + for connector in ( + _server_connector("db.example.org", 5432), + _server_connector("db.example.org", 5432, several_servers=True), + ): + src = self._source(connector, source_id="measurements_v1") + assert src.source_id == "measurements_v1" + connector.current_location.assert_not_called() diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index 0a94410b8..fd89c818a 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -260,3 +260,190 @@ def double_response(trial: int, response: float) -> float: tag_values = sorted([tags["session_id"] for tags, _ in fn_outputs[0]]) assert tag_values == ["s1", "s2", "s3"] + + +# --------------------------------------------------------------------------- +# The default source id names the server (ITL-1267) +# --------------------------------------------------------------------------- + + +def _server() -> dict[str, str]: + """The test server's connection parameters, from the PG* environment.""" + return { + "host": os.environ.get("PGHOST", "localhost"), + "port": os.environ.get("PGPORT", "5432"), + "dbname": os.environ.get("PGDATABASE", "testdb"), + "user": os.environ.get("PGUSER", "postgres"), + "password": os.environ.get("PGPASSWORD", "postgres"), + } + + +def _keyword_dsn(schema: str, **params: str | None) -> str: + """A keyword DSN for the test server; a parameter given as None is left out.""" + merged: dict[str, str | None] = {**_server(), **params} + parts = [f"{key}={value}" for key, value in merged.items() if value is not None] + return " ".join([*parts, f"options=-csearch_path={schema}"]) + + +@pytest.fixture +def server_table(pg_schema: str) -> str: + """A one-row table ``t`` in the test schema; returns the schema.""" + with psycopg.connect(_keyword_dsn(pg_schema)) as conn: + with conn.cursor() as cur: + cur.execute('CREATE TABLE "t" (k TEXT PRIMARY KEY, x INTEGER)') + cur.execute("INSERT INTO \"t\" VALUES ('a', 1)") + conn.commit() + return pg_schema + + +@pytest.fixture +def no_server_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep the PG* host and port variables out of the DSNs a test builds.""" + for envvar in ("PGHOST", "PGHOSTADDR", "PGPORT"): + monkeypatch.delenv(envvar, raising=False) + + +def _source_id(dsn: str) -> str: + from orcapod.core.sources import PostgreSQLTableSource + + return PostgreSQLTableSource(dsn, "t", tag_only_columns=True).source_id + + +def _expected(host: str, schema: str, port: str | None = None) -> str: + server = _server() + return ( + f"postgresql_table:{host}:{port or server['port']}/" + f"{server['dbname']}.{schema}.t" + ) + + +def _requires_localhost() -> None: + if _server()["host"] != "localhost": + pytest.skip("needs the test server at PGHOST=localhost, as in CI") + + +@pytest.mark.postgres +class TestDefaultSourceIdOnTheServer: + """What the connection reports, measured on the test server. + + The CI server is reached as ``localhost:5432`` over TCP; Unix sockets are covered + by unit tests only (the CI server runs in a container and has no local socket). + """ + + def test_uri_and_keyword_dsn_give_one_id(self, server_table: str) -> None: + server = _server() + uri = ( + f"postgresql://{server['user']}:{server['password']}@{server['host']}:" + f"{server['port']}/{server['dbname']}" + f"?options=-csearch_path%3D{server_table}" + ) + ids = [_source_id(uri), _source_id(_keyword_dsn(server_table))] + assert ids == [_expected(server["host"].lower(), server_table)] * 2 + + def test_id_never_holds_user_or_password(self, server_table: str) -> None: + server = _server() + uri = ( + f"postgresql://{server['user']}:{server['password']}@{server['host']}:" + f"{server['port']}/{server['dbname']}" + f"?options=-csearch_path%3D{server_table}" + ) + for dsn in (uri, _keyword_dsn(server_table)): + location = _source_id(dsn).removeprefix("postgresql_table:") + assert server["user"] not in location + assert server["password"] not in location + + def test_upper_case_host_name_gives_the_lower_case_id( + self, server_table: str + ) -> None: + _requires_localhost() + ids = [ + _source_id(_keyword_dsn(server_table, host=host)) + for host in ("LOCALHOST", "localhost", "LocalHost") + ] + assert ids == [_expected("localhost", server_table)] * 3 + + def test_omitted_port_is_written_as_the_port_used( + self, server_table: str, no_server_env: None + ) -> None: + if _server()["port"] != "5432": + pytest.skip("needs the test server on the default port 5432") + omitted = _source_id(_keyword_dsn(server_table, host="localhost", port=None)) + given = _source_id(_keyword_dsn(server_table, host="localhost", port="5432")) + assert omitted == given == _expected("localhost", server_table, "5432") + + def test_two_spellings_of_one_server_give_two_ids(self, server_table: str) -> None: + _requires_localhost() + ids = [ + _source_id(_keyword_dsn(server_table, host=host)) + for host in ("localhost", "127.0.0.1") + ] + assert ids == [ + _expected("localhost", server_table), + _expected("127.0.0.1", server_table), + ] + + def test_hostaddr_alone_names_the_address( + self, server_table: str, no_server_env: None + ) -> None: + _requires_localhost() + dsn = _keyword_dsn(server_table, host=None, hostaddr="127.0.0.1") + assert _source_id(dsn) == _expected("127.0.0.1", server_table) + + def test_host_with_hostaddr_names_the_host( + self, server_table: str, no_server_env: None + ) -> None: + _requires_localhost() + dsn = _keyword_dsn(server_table, host="LocalHost", hostaddr="127.0.0.1") + assert _source_id(dsn) == _expected("localhost", server_table) + + def test_ipv6_host_is_bracketed_and_exploded(self, server_table: str) -> None: + _requires_localhost() + dsn = _keyword_dsn(server_table, host="::1") + try: + psycopg.connect(dsn).close() + except psycopg.OperationalError: + pytest.skip("the test server is not reachable over IPv6") + assert _source_id(dsn) == _expected( + "[0000:0000:0000:0000:0000:0000:0000:0001]", server_table + ) + + @pytest.mark.parametrize("hosts", ["localhost,127.0.0.1", "127.0.0.1,localhost"]) + def test_several_hosts_in_the_dsn_have_no_default( + self, server_table: str, hosts: str + ) -> None: + _requires_localhost() + from orcapod.core.sources import PostgreSQLTableSource + + dsn = _keyword_dsn(server_table, host=hosts) + with pytest.raises(ValueError, match="several servers"): + _source_id(dsn) + given = PostgreSQLTableSource( + dsn, "t", source_id="t_on_the_pool", tag_only_columns=True + ) + assert given.source_id == "t_on_the_pool" + + def test_several_hosts_from_pghost_have_no_default( + self, server_table: str, no_server_env: None, monkeypatch: pytest.MonkeyPatch + ) -> None: + _requires_localhost() + monkeypatch.setenv("PGHOST", "localhost,127.0.0.1") + with pytest.raises(ValueError, match="several servers"): + _source_id(_keyword_dsn(server_table, host=None)) + + def test_several_hosts_from_a_service_file_have_no_default( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + tmp_path, + ) -> None: + _requires_localhost() + server = _server() + service_file = tmp_path / "pg_service.conf" + service_file.write_text( + f"[pool]\nhost=localhost,127.0.0.1\nport={server['port']}\n" + ) + monkeypatch.setenv("PGSERVICEFILE", str(service_file)) + dsn = _keyword_dsn(server_table, host=None, port=None, service="pool") + with pytest.raises(ValueError, match="several servers"): + _source_id(dsn) diff --git a/tests/test_core/sources/test_source_check_for_new_data.py b/tests/test_core/sources/test_source_check_for_new_data.py index 385b7e7fa..49db73e24 100644 --- a/tests/test_core/sources/test_source_check_for_new_data.py +++ b/tests/test_core/sources/test_source_check_for_new_data.py @@ -482,7 +482,8 @@ def _pg_connector(keys: list[int]) -> MagicMock: connector = MagicMock() connector.get_table_names.return_value = ["t"] connector.get_pk_columns.return_value = ["k"] - connector.current_location.return_value = ("orcapod", "public") + connector.current_location.return_value = ("localhost", 5432, "orcapod", "public") + connector.names_several_servers.return_value = False connector.get_column_info.return_value = [ ColumnInfo("k", pa.int64(), False), ColumnInfo("x", pa.int64(), False), @@ -756,7 +757,8 @@ def _connector_without_column_info(x: list[int | None]) -> MagicMock: connector = MagicMock() connector.get_table_names.return_value = ["t"] connector.get_pk_columns.return_value = ["k"] - connector.current_location.return_value = ("orcapod", "public") + connector.current_location.return_value = ("localhost", 5432, "orcapod", "public") + connector.names_several_servers.return_value = False connector.get_column_info.return_value = [] table = pa.table( {"k": pa.array(range(len(x)), pa.int64()), "x": pa.array(x, pa.int64())} diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index 545d7b096..7d7e1c690 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -309,3 +309,122 @@ def test_get_pk_columns_no_pk(self) -> None: result = connector.get_pk_columns("my_table") assert result == [] connector._conn = None + + +class TestServerLocationUnit: + """``current_location`` and ``names_several_servers`` (ITL-1267), mocked connection. + + The values a live server reports are asserted by the postgres-marked tests in + ``tests/test_core/sources/test_postgresql_table_source_integration.py``. + """ + + @staticmethod + def _connector( + dsn: str = "postgresql://localhost/test", + *, + host: str = "localhost", + port: int = 5432, + parameters: dict[str, str] | None = None, + ) -> PostgreSQLConnector: + with patch("psycopg.connect") as mock_connect: + conn = MagicMock() + conn.info.host = host + conn.info.port = port + conn.info.get_parameters.return_value = ( + {"host": host} if parameters is None else parameters + ) + cursor = MagicMock() + cursor.__enter__ = lambda s: s + cursor.__exit__ = MagicMock(return_value=False) + cursor.fetchone.return_value = ("testdb", "public") + conn.cursor.return_value = cursor + mock_connect.return_value = conn + return PostgreSQLConnector(dsn) + + @pytest.mark.parametrize( + ("host", "port"), + [("db.example.org", 5433), ("/var/run/postgresql", 5432), ("::1", 6543)], + ) + def test_current_location_reports_the_connection( + self, host: str, port: int + ) -> None: + connector = self._connector(host=host, port=port) + assert connector.current_location() == (host, port, "testdb", "public") + connector._conn = None + + @pytest.mark.parametrize( + "dsn", + [ + "host=a.example.org,b.example.org port=5432 dbname=x", + "host=a.example.org,b.example.org port=5432,5433 dbname=x", + "postgresql://u:p@a.example.org:5432,b.example.org:5433/x", + "postgresql://u@b.example.org,a.example.org/x", + "hostaddr=192.0.2.1,192.0.2.2 dbname=x", + ], + ) + def test_several_hosts_in_the_dsn( + self, dsn: str, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.delenv("PGHOST", raising=False) + monkeypatch.delenv("PGHOSTADDR", raising=False) + connector = self._connector(dsn) + assert connector.names_several_servers() + connector._conn = None + + @pytest.mark.parametrize( + ("envvar", "value"), + [ + ("PGHOST", "a.example.org,b.example.org"), + ("PGHOSTADDR", "192.0.2.1,192.0.2.2"), + ], + ) + def test_several_hosts_from_the_environment( + self, envvar: str, value: str, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.delenv("PGHOST", raising=False) + monkeypatch.delenv("PGHOSTADDR", raising=False) + monkeypatch.setenv(envvar, value) + connector = self._connector("dbname=x user=u") + assert connector.names_several_servers() + connector._conn = None + + def test_the_dsn_host_overrides_the_environment( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv("PGHOST", "a.example.org,b.example.org") + monkeypatch.delenv("PGHOSTADDR", raising=False) + connector = self._connector("host=db.example.org dbname=x") + assert not connector.names_several_servers() + connector._conn = None + + @pytest.mark.parametrize("key", ["host", "hostaddr"]) + def test_several_hosts_the_connection_reports( + self, key: str, monkeypatch: pytest.MonkeyPatch + ) -> None: + # A service file can name several hosts; the DSN then names none, and only + # the connection's own parameters show them. + monkeypatch.delenv("PGHOST", raising=False) + monkeypatch.delenv("PGHOSTADDR", raising=False) + connector = self._connector( + "service=pool dbname=x", + parameters={key: "a.example.org,b.example.org"}, + ) + assert connector.names_several_servers() + connector._conn = None + + @pytest.mark.parametrize( + "dsn", + [ + "postgresql://u:p@db.example.org:5432/x", + "host=db.example.org port=5432 dbname=x", + "host=db.example.org hostaddr=192.0.2.1 dbname=x", + "host=/var/run/postgresql dbname=x", + "dbname=x", + ], + ) + def test_one_server(self, dsn: str, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("PGHOST", raising=False) + monkeypatch.delenv("PGHOSTADDR", raising=False) + connector = self._connector(dsn, parameters={"host": "db.example.org"}) + assert not connector.names_several_servers() + connector._conn = None From 3ca82e1ee6abb5f3f25ae529aa6d6256fd532896 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 19:04:19 -0800 Subject: [PATCH 2/7] fix(sources): no default PostgreSQL source id for a host beside a hostaddr (ITL-1267) Answers the CodeRabbit review of PR 452. Connection parameters that give a host beside a hostaddr that is not that address (in the DSN, through PGHOST/PGHOSTADDR, or in a service file) now give no default source id: libpq sends the connection to the address, so the host name does not name the server, and two such DSNs with one host and two addresses would have shared an id. A hostaddr alone (or equal to the host) still names the server by that address. PostgreSQLConnector.given_server replaces names_several_servers: it returns the host and hostaddr the user gave (DSN, else the environment, else a service file through the reported parameters), never the hostaddr psycopg adds when it resolves a host itself; the source refuses several servers and a host beside a hostaddr from it. Integration tests: the server settings are read once at import, before no_server_env clears PGHOST/PGPORT, and the id is compared exactly with the expected location instead of by credential substrings. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 5 +- CLAUDE.md | 5 +- changelog.d/ITL-1267.md | 8 +- docs/concepts/sources.md | 5 +- docs/reference/hashing.md | 13 +- .../core/sources/postgresql_table_source.py | 23 +- src/orcapod/databases/postgresql_connector.py | 46 ++-- .../sources/test_postgresql_table_source.py | 68 ++++- ...est_postgresql_table_source_integration.py | 157 ++++++++++-- .../sources/test_source_check_for_new_data.py | 4 +- .../test_postgresql_connector.py | 240 +++++++++++++----- 11 files changed, 438 insertions(+), 136 deletions(-) diff --git a/.zed/rules b/.zed/rules index 3817de476..a87bf0bbf 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1105,8 +1105,9 @@ data. The rules: delta_table:, sqlite_table::main.
, postgresql_table::/..
(the server the connection reached, as libpq reports it: a host name lower-cased, an IPv6 address bracketed and - exploded, a socket directory as given, the port always a number; a DSN naming several - servers has no default; developer, November 18, 2026, ITL-1267), + exploded, a socket directory as given, the port always a number; parameters naming several + servers, or a host beside a hostaddr that is not that address, give no default; + developer, November 18, 2026, ITL-1267), spiraldb_table:..
@
(developer, November 16, 2026); a location whose parts hold their separator has no default (source_ids.joined_location). A DBTableSource used directly (a generic connector, no database address) has no default: diff --git a/CLAUDE.md b/CLAUDE.md index 145de5d95..837860e03 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1149,8 +1149,9 @@ data. The rules: `delta_table:`, `sqlite_table::main.
`, `postgresql_table::/..
` (the server the connection reached, as libpq reports it: a host name lower-cased, an IPv6 address bracketed and - exploded, a socket directory as given, the port always a number; a DSN naming several - servers has no default; developer, November 18, 2026, ITL-1267), + exploded, a socket directory as given, the port always a number; parameters naming several + servers, or a host beside a `hostaddr` that is not that address, give no default; + developer, November 18, 2026, ITL-1267), `spiraldb_table:..
@
` (developer, November 16, 2026); a location whose parts hold their separator has no default (`source_ids.joined_location`). A `DBTableSource` used directly (a generic connector, no database address) has no default: diff --git a/changelog.d/ITL-1267.md b/changelog.d/ITL-1267.md index 403999c47..ee71e5373 100644 --- a/changelog.d/ITL-1267.md +++ b/changelog.d/ITL-1267.md @@ -11,5 +11,9 @@ `source_id` you give is used as before, and a saved job keeps the id it was saved with. - A PostgreSQL source whose DSN, `PGHOST` / `PGHOSTADDR` setting or service file names several servers (`host=a,b`) has no default source id and raises `ValueError` unless it is given a - `source_id`: the server reached can change from one connection to the next. A database, - schema or table name holding `/` has no default either, as one holding `.` already had. + `source_id`: the server reached can change from one connection to the next. So does one + whose parameters give a host beside a `hostaddr` that is not that address + (`host=db.example.org hostaddr=192.0.2.1`): the connection is sent to the address, so the + host name does not name the server. A `hostaddr` given alone names the server by that + address. A database, schema or table name holding `/` has no default either, as one holding + `.` already had. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 323c22d47..cb395f666 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -40,8 +40,9 @@ where it lives (`sqlite_table::main.
`, `postgresql_table::/..
`, with the server the connection reached; the [hashing reference](../reference/hashing.md#default-source-ids-and-row-identifiers) has -every form). A PostgreSQL DSN that names several servers (`host=a,b`) has no default: give -such a source a `source_id`. `DBTableSource`, the base they share, can also be used directly +every form). A PostgreSQL DSN that names several servers (`host=a,b`), or gives a host +beside a `hostaddr` (`host=db.example.org hostaddr=192.0.2.1`), has no default: give such a +source a `source_id`. `DBTableSource`, the base they share, can also be used directly over any connector; a connector gives no address of its database, so it then has no default and needs a `source_id`. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 87dd0ad5d..d1a9e22f6 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -186,8 +186,8 @@ holding `@`. Such a source needs a `source_id`. A PostgreSQL default names the server the connection reached (developer, November 18, 2026, ITL-1267), as libpq reports it, so one database, schema and table name on two servers gives -two ids. The host is the name or address as given (with `host` and `hostaddr` both given, -the host), or the directory of a Unix-domain socket; never the address a name resolved to. +two ids. The host is the name or address as given, or the directory of a Unix-domain socket; +never the address a name resolved to. A `hostaddr` given alone is the host. A host name is written in lower case (`DB.Example.ORG` and `db.example.org` are one id); an IPv6 address in brackets and in its exploded form, which holds no `::` (`[0000:0000:0000:0000:0000:0000:0000:0001]` for `::1`); an IPv4 address and a socket @@ -195,8 +195,13 @@ directory as given. The port is always the number used, the default `5432` inclu DSN with `port=5432` and one without it give one id. Two spellings of one server are two ids (`localhost` and `127.0.0.1`), as two spellings of one CSV path are. A DSN, a `PGHOST` or `PGHOSTADDR` setting or a service file that names several servers (`host=a,b`) gives no -default: the server reached can change from one connection to the next. No user name, -password or other connection parameter enters the id. +default: the server reached can change from one connection to the next. Neither do +parameters that give a host beside a `hostaddr` that is not that address +(`host=db.example.org hostaddr=192.0.2.1`): libpq sends the connection to the address, so +the host name does not name the server, and two such DSNs with one host and two addresses +would share an id. A name that DNS, a hosts file or a tunnel sends to another server is not +seen in the parameters: two servers reached under one name that way share a default id and +need a `source_id`. No user name, password or other connection parameter enters the id. A row's record id is its row identifier (site 5), chosen by `record_id_columns` (a column name or several, in key order; every source accepts it): diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index d440094ef..97c0c4ce0 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -123,8 +123,8 @@ class PostgreSQLTableSource(DBTableSource): primary key (a table without one is refused); ``()``: the position. source_id: Canonical source name. Defaults to ``postgresql_table::/..
`` - (``postgresql_table_address``); a DSN that names several servers has - no default. + (``postgresql_table_address``); connection parameters that name + several servers, or a host beside a ``hostaddr``, give no default. label: Human-readable label for this source node. data_context: Data context governing type conversion and hashing. config: OrcaPod configuration. @@ -196,12 +196,14 @@ def _table_address(self, connector: DBConnectorProtocol, table_name: str) -> str The table's address. Raises: - ValueError: If the connection parameters name several servers: the one - reached can change from one connection to the next, so it is no - name for the table. + ValueError: If the connection parameters name several servers (the one + reached can change from one connection to the next), or give a + ``hostaddr`` beside a host that is not that address (the connection + is sent to the address, so the host does not name the server). """ pg = cast("PostgreSQLConnector", connector) - if pg.names_several_servers(): + host, hostaddr = pg.given_server() + if "," in host or "," in hostaddr: raise ValueError( f"the connection parameters of the PostgreSQL source over table " f"{table_name!r} (its DSN, PGHOST or PGHOSTADDR, or a service file) " @@ -209,6 +211,15 @@ def _table_address(self, connector: DBConnectorProtocol, table_name: str) -> str "connection to the next, so the table has no default source id; give " "the source a source_id" ) + if host and hostaddr and host != hostaddr: + raise ValueError( + f"the connection parameters of the PostgreSQL source over table " + f"{table_name!r} (its DSN, PGHOST or PGHOSTADDR, or a service file) " + f"give the host {host!r} and the address {hostaddr!r}: the connection " + "is sent to the address, so the host name alone does not identify " + "the server, and the table has no default source id; give the source " + "a source_id" + ) host, port, database, schema = pg.current_location() return postgresql_table_address(host, port, database, schema, table_name) diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 5151b80d5..6f88248bd 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -410,9 +410,9 @@ def current_location(self) -> tuple[str, int, str, str]: ``(host, port, current_database(), current_schema())``: where the connector finds its tables. The host and port are what libpq reports for the live connection (``PQhost``, ``PQport``): the host name or IP address as given - (with ``host`` and ``hostaddr`` both given, the host), or the directory of a - Unix-domain socket; the port is the one used, the compiled default when none - was given. Never the resolved address, the user, the password or any other + (with ``host`` and ``hostaddr`` both given, the host; ``given_server`` tells + that case apart), or the directory of a Unix-domain socket; the port is the + one used, the compiled default when none was given. Never the resolved address, the user, the password or any other connection parameter (ITL-1267). Returns: @@ -431,30 +431,36 @@ def current_location(self) -> tuple[str, int, str, str]: raise ValueError("the PostgreSQL connection has no current schema") return str(host), int(port), str(row[0]), str(row[1]) - def names_several_servers(self) -> bool: - """Return whether the connection parameters name more than one server. + def given_server(self) -> tuple[str, str]: + """Return the ``host`` and ``hostaddr`` the user gave the connection. - libpq accepts a comma-separated list of hosts (``host=a,b``, or - ``postgresql://a:5432,b:5433/db``) and connects to the first that answers. - The list may come from the DSN, from ``PGHOST`` / ``PGHOSTADDR`` when the DSN - names no host, or from a service file; the first two are read from the DSN - and the environment, a service file from the parameters the connection - reports (psycopg tries the hosts of the DSN and the environment one by one, - so its connection reports only the one it reached). + Each is read from the DSN, else from ``PGHOST`` / ``PGHOSTADDR``; when + neither names a host, libpq takes the host (and a ``hostaddr`` the DSN and + the environment do not give) from a service file, which only the parameters + the connection reports show. Never the parameters psycopg adds: psycopg + resolves a host of the DSN or the environment itself and passes the address + it reached as ``hostaddr``, so a reported ``hostaddr`` is the user's only when + no host came from the DSN or the environment. A value may be a + comma-separated list (``host=a,b``, ``postgresql://a:5432,b:5433/db``): libpq + then connects to the first server that answers. Returns: - ``True`` when ``host`` or ``hostaddr`` holds more than one entry. + The host and the host address as given, each ``""`` when none is. """ from psycopg.conninfo import conninfo_to_dict given = conninfo_to_dict(self._dsn) - with self._lock: - reported = self._require_open().info.get_parameters() - for key, envvar in (("host", "PGHOST"), ("hostaddr", "PGHOSTADDR")): - value = given[key] if key in given else os.environ.get(envvar) - if "," in str(value or "") or "," in reported.get(key, ""): - return True - return False + + def supplied(key: str, envvar: str) -> str: + return str((given[key] if key in given else os.environ.get(envvar)) or "") + + host, hostaddr = supplied("host", "PGHOST"), supplied("hostaddr", "PGHOSTADDR") + if not host: + with self._lock: + reported = self._require_open().info.get_parameters() + host = reported.get("host", "") + hostaddr = hostaddr or reported.get("hostaddr", "") + return host, hostaddr def get_pk_columns(self, table_name: str) -> list[str]: """Return primary-key column names in key-sequence order.""" diff --git a/tests/test_core/sources/test_postgresql_table_source.py b/tests/test_core/sources/test_postgresql_table_source.py index 61c2d60d2..06d46410e 100644 --- a/tests/test_core/sources/test_postgresql_table_source.py +++ b/tests/test_core/sources/test_postgresql_table_source.py @@ -1,6 +1,7 @@ """Unit tests for PostgreSQLTableSource.""" from __future__ import annotations +from typing import ClassVar from unittest.mock import MagicMock, patch import pyarrow as pa import pytest @@ -74,7 +75,7 @@ def _make_mock_connector( mock.get_table_names.return_value = table_names mock.get_pk_columns.return_value = pk_columns mock.current_location.return_value = ("localhost", 5432, "orcapod", "public") - mock.names_several_servers.return_value = False + mock.given_server.return_value = ("localhost", "") mock.get_column_info.return_value = [] mock.iter_batches.return_value = iter(batches) return mock @@ -553,12 +554,16 @@ def _server_connector( database: str = "orcapod", schema: str = "public", *, - several_servers: bool = False, + given: tuple[str, str] | None = None, ) -> MagicMock: - """A mocked connector whose connection reports ``host``, ``port`` and location.""" + """A mocked connector whose connection reports ``host``, ``port`` and location. + + ``given`` is the ``host`` and ``hostaddr`` the user gave (``given_server``); + by default the host alone. + """ mock = _make_mock_connector() mock.current_location.return_value = (host, port, database, schema) - mock.names_several_servers.return_value = several_servers + mock.given_server.return_value = (host, "") if given is None else given return mock @@ -718,16 +723,53 @@ def test_id_never_holds_user_or_password(self, dsn: str) -> None: assert "alice" not in source_id assert "s3cret" not in source_id - def test_several_servers_have_no_default(self) -> None: - connector = _server_connector("db.example.org", 5432, several_servers=True) + SEVERAL_SERVERS: ClassVar[list[tuple[str, str]]] = [ + ("a.example.org,b.example.org", ""), + ("b.example.org,a.example.org", ""), + ("", "192.0.2.1,192.0.2.2"), + ("a.example.org,b.example.org", "192.0.2.1,192.0.2.2"), + ] + # A host beside a hostaddr that is not that address: the connection is sent to + # the address, so the host does not name the server. + HOST_BESIDE_HOSTADDR: ClassVar[list[tuple[str, str]]] = [ + ("db.example.org", "192.0.2.1"), + ("db.example.org", "192.0.2.2"), + ("localhost", "127.0.0.1"), + ("/var/run/postgresql", "192.0.2.1"), + ("192.0.2.1", "192.0.2.2"), + ] + + @pytest.mark.parametrize("given", SEVERAL_SERVERS) + def test_several_servers_have_no_default(self, given: tuple[str, str]) -> None: + connector = _server_connector("db.example.org", 5432, given=given) with pytest.raises(ValueError, match="several servers.*source_id"): self._source(connector) + connector.current_location.assert_not_called() - def test_given_source_id_is_used_as_given(self) -> None: - for connector in ( - _server_connector("db.example.org", 5432), - _server_connector("db.example.org", 5432, several_servers=True), + @pytest.mark.parametrize("given", HOST_BESIDE_HOSTADDR) + def test_host_beside_hostaddr_has_no_default(self, given: tuple[str, str]) -> None: + connector = _server_connector(given[0], 5432, given=given) + with pytest.raises( + ValueError, match="host name alone does not identify.*source_id" ): - src = self._source(connector, source_id="measurements_v1") - assert src.source_id == "measurements_v1" - connector.current_location.assert_not_called() + self._source(connector) + connector.current_location.assert_not_called() + + def test_hostaddr_alone_or_equal_to_the_host_names_the_address(self) -> None: + # libpq reports the address as the host when no host is given; a host that + # is the address itself names it too. + for given in [("", "192.0.2.1"), ("192.0.2.1", "192.0.2.1")]: + connector = _server_connector("192.0.2.1", 5432, given=given) + assert self._source(connector).source_id == ( + "postgresql_table:192.0.2.1:5432/orcapod.public.measurements" + ) + + @pytest.mark.parametrize( + "given", [("db.example.org", ""), *SEVERAL_SERVERS, *HOST_BESIDE_HOSTADDR] + ) + def test_given_source_id_is_used_as_given(self, given: tuple[str, str]) -> None: + connector = _server_connector("db.example.org", 5432, given=given) + src = self._source(connector, source_id="measurements_v1") + assert src.source_id == "measurements_v1" + connector.current_location.assert_not_called() + connector.given_server.assert_not_called() diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index fd89c818a..2d6b9fbd5 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -18,7 +18,8 @@ import os import uuid -from collections.abc import Iterator +from collections.abc import Iterator, Mapping +from types import MappingProxyType import pytest @@ -267,20 +268,28 @@ def double_response(trial: int, response: float) -> float: # --------------------------------------------------------------------------- -def _server() -> dict[str, str]: - """The test server's connection parameters, from the PG* environment.""" - return { +# The test server's connection parameters, read from the PG* environment once, when +# the module is imported: before any fixture (``no_server_env``) or test changes it. +_SERVER: Mapping[str, str] = MappingProxyType( + { "host": os.environ.get("PGHOST", "localhost"), "port": os.environ.get("PGPORT", "5432"), "dbname": os.environ.get("PGDATABASE", "testdb"), "user": os.environ.get("PGUSER", "postgres"), "password": os.environ.get("PGPASSWORD", "postgres"), } +) def _keyword_dsn(schema: str, **params: str | None) -> str: - """A keyword DSN for the test server; a parameter given as None is left out.""" - merged: dict[str, str | None] = {**_server(), **params} + """A keyword DSN for the test server; a parameter given as None is left out. + + The parameters given come after the server's others, in the order given. + """ + merged: dict[str, str | None] = { + **{key: value for key, value in _SERVER.items() if key not in params}, + **params, + } parts = [f"{key}={value}" for key, value in merged.items() if value is not None] return " ".join([*parts, f"options=-csearch_path={schema}"]) @@ -310,15 +319,14 @@ def _source_id(dsn: str) -> str: def _expected(host: str, schema: str, port: str | None = None) -> str: - server = _server() return ( - f"postgresql_table:{host}:{port or server['port']}/" - f"{server['dbname']}.{schema}.t" + f"postgresql_table:{host}:{port or _SERVER['port']}/" + f"{_SERVER['dbname']}.{schema}.t" ) def _requires_localhost() -> None: - if _server()["host"] != "localhost": + if _SERVER["host"] != "localhost": pytest.skip("needs the test server at PGHOST=localhost, as in CI") @@ -331,26 +339,26 @@ class TestDefaultSourceIdOnTheServer: """ def test_uri_and_keyword_dsn_give_one_id(self, server_table: str) -> None: - server = _server() uri = ( - f"postgresql://{server['user']}:{server['password']}@{server['host']}:" - f"{server['port']}/{server['dbname']}" + f"postgresql://{_SERVER['user']}:{_SERVER['password']}@{_SERVER['host']}:" + f"{_SERVER['port']}/{_SERVER['dbname']}" f"?options=-csearch_path%3D{server_table}" ) ids = [_source_id(uri), _source_id(_keyword_dsn(server_table))] - assert ids == [_expected(server["host"].lower(), server_table)] * 2 + assert ids == [_expected(_SERVER["host"].lower(), server_table)] * 2 def test_id_never_holds_user_or_password(self, server_table: str) -> None: - server = _server() + # Both DSNs carry the user and the password; the id is exactly the host, the + # port and the three-part name, with room for nothing else. (A substring + # check would fail a correct id whenever the user's name is also the + # database's, as with PGUSER=postgres PGDATABASE=postgres.) uri = ( - f"postgresql://{server['user']}:{server['password']}@{server['host']}:" - f"{server['port']}/{server['dbname']}" + f"postgresql://{_SERVER['user']}:{_SERVER['password']}@{_SERVER['host']}:" + f"{_SERVER['port']}/{_SERVER['dbname']}" f"?options=-csearch_path%3D{server_table}" ) for dsn in (uri, _keyword_dsn(server_table)): - location = _source_id(dsn).removeprefix("postgresql_table:") - assert server["user"] not in location - assert server["password"] not in location + assert _source_id(dsn) == _expected(_SERVER["host"].lower(), server_table) def test_upper_case_host_name_gives_the_lower_case_id( self, server_table: str @@ -365,7 +373,7 @@ def test_upper_case_host_name_gives_the_lower_case_id( def test_omitted_port_is_written_as_the_port_used( self, server_table: str, no_server_env: None ) -> None: - if _server()["port"] != "5432": + if _SERVER["port"] != "5432": pytest.skip("needs the test server on the default port 5432") omitted = _source_id(_keyword_dsn(server_table, host="localhost", port=None)) given = _source_id(_keyword_dsn(server_table, host="localhost", port="5432")) @@ -389,11 +397,111 @@ def test_hostaddr_alone_names_the_address( dsn = _keyword_dsn(server_table, host=None, hostaddr="127.0.0.1") assert _source_id(dsn) == _expected("127.0.0.1", server_table) - def test_host_with_hostaddr_names_the_host( + def test_host_equal_to_hostaddr_names_the_address( self, server_table: str, no_server_env: None ) -> None: _requires_localhost() - dsn = _keyword_dsn(server_table, host="LocalHost", hostaddr="127.0.0.1") + dsn = _keyword_dsn(server_table, host="127.0.0.1", hostaddr="127.0.0.1") + assert _source_id(dsn) == _expected("127.0.0.1", server_table) + + @pytest.mark.parametrize( + "order", + [("host", "hostaddr"), ("hostaddr", "host")], + ids=["host-first", "hostaddr-first"], + ) + @pytest.mark.parametrize("form", ["keyword", "uri"]) + def test_host_beside_hostaddr_in_the_dsn_has_no_default( + self, + server_table: str, + no_server_env: None, + form: str, + order: tuple[str, str], + ) -> None: + _requires_localhost() + from orcapod.core.sources import PostgreSQLTableSource + + server = {"host": "LocalHost", "hostaddr": "127.0.0.1"} + if form == "keyword": + dsn = _keyword_dsn(server_table, **{key: server[key] for key in order}) + else: + query = "&".join(f"{key}={server[key]}" for key in order) + dsn = ( + f"postgresql://{_SERVER['user']}:{_SERVER['password']}@:" + f"{_SERVER['port']}/{_SERVER['dbname']}?{query}" + f"&options=-csearch_path%3D{server_table}" + ) + with pytest.raises(ValueError, match="host name alone does not identify"): + _source_id(dsn) + given = PostgreSQLTableSource( + dsn, "t", source_id="t_by_address", tag_only_columns=True + ) + assert given.source_id == "t_by_address" + + @pytest.mark.parametrize( + ("dsn_params", "env"), + [ + ({"host": "localhost"}, {"PGHOSTADDR": "127.0.0.1"}), + ({"hostaddr": "127.0.0.1"}, {"PGHOST": "localhost"}), + ({}, {"PGHOST": "localhost", "PGHOSTADDR": "127.0.0.1"}), + ({}, {"PGHOSTADDR": "127.0.0.1", "PGHOST": "localhost"}), + ], + ids=["dsn-host-env-addr", "env-host-dsn-addr", "env-both", "env-both-reversed"], + ) + def test_host_beside_hostaddr_from_the_environment_has_no_default( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + dsn_params: dict[str, str], + env: dict[str, str], + ) -> None: + _requires_localhost() + for envvar, value in env.items(): + monkeypatch.setenv(envvar, value) + dsn = _keyword_dsn(server_table, **{"host": None, **dsn_params}) + with pytest.raises(ValueError, match="host name alone does not identify"): + _source_id(dsn) + + @pytest.mark.parametrize( + ("service", "dsn_params"), + [ + ("host=localhost\nhostaddr=127.0.0.1", {}), + ("hostaddr=127.0.0.1\nhost=localhost", {}), + ("host=localhost", {"hostaddr": "127.0.0.1"}), + ], + ids=["service-both", "service-both-reversed", "service-host-dsn-addr"], + ) + def test_host_beside_hostaddr_from_a_service_file_has_no_default( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + tmp_path, + service: str, + dsn_params: dict[str, str], + ) -> None: + _requires_localhost() + service_file = tmp_path / "pg_service.conf" + service_file.write_text(f"[one]\n{service}\nport={_SERVER['port']}\n") + monkeypatch.setenv("PGSERVICEFILE", str(service_file)) + dsn = _keyword_dsn( + server_table, **{"host": None, "port": None, "service": "one", **dsn_params} + ) + with pytest.raises(ValueError, match="host name alone does not identify"): + _source_id(dsn) + + def test_host_from_a_service_file_names_the_host( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + tmp_path, + ) -> None: + _requires_localhost() + service_file = tmp_path / "pg_service.conf" + service_file.write_text(f"[one]\nhost=LocalHost\nport={_SERVER['port']}\n") + monkeypatch.setenv("PGSERVICEFILE", str(service_file)) + dsn = _keyword_dsn(server_table, host=None, port=None, service="one") assert _source_id(dsn) == _expected("localhost", server_table) def test_ipv6_host_is_bracketed_and_exploded(self, server_table: str) -> None: @@ -438,10 +546,9 @@ def test_several_hosts_from_a_service_file_have_no_default( tmp_path, ) -> None: _requires_localhost() - server = _server() service_file = tmp_path / "pg_service.conf" service_file.write_text( - f"[pool]\nhost=localhost,127.0.0.1\nport={server['port']}\n" + f"[pool]\nhost=localhost,127.0.0.1\nport={_SERVER['port']}\n" ) monkeypatch.setenv("PGSERVICEFILE", str(service_file)) dsn = _keyword_dsn(server_table, host=None, port=None, service="pool") diff --git a/tests/test_core/sources/test_source_check_for_new_data.py b/tests/test_core/sources/test_source_check_for_new_data.py index 49db73e24..8c4d14d6a 100644 --- a/tests/test_core/sources/test_source_check_for_new_data.py +++ b/tests/test_core/sources/test_source_check_for_new_data.py @@ -483,7 +483,7 @@ def _pg_connector(keys: list[int]) -> MagicMock: connector.get_table_names.return_value = ["t"] connector.get_pk_columns.return_value = ["k"] connector.current_location.return_value = ("localhost", 5432, "orcapod", "public") - connector.names_several_servers.return_value = False + connector.given_server.return_value = ("localhost", "") connector.get_column_info.return_value = [ ColumnInfo("k", pa.int64(), False), ColumnInfo("x", pa.int64(), False), @@ -758,7 +758,7 @@ def _connector_without_column_info(x: list[int | None]) -> MagicMock: connector.get_table_names.return_value = ["t"] connector.get_pk_columns.return_value = ["k"] connector.current_location.return_value = ("localhost", 5432, "orcapod", "public") - connector.names_several_servers.return_value = False + connector.given_server.return_value = ("localhost", "") connector.get_column_info.return_value = [] table = pa.table( {"k": pa.array(range(len(x)), pa.int64()), "x": pa.array(x, pa.int64())} diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index 7d7e1c690..c83d4b7aa 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -312,7 +312,7 @@ def test_get_pk_columns_no_pk(self) -> None: class TestServerLocationUnit: - """``current_location`` and ``names_several_servers`` (ITL-1267), mocked connection. + """``current_location`` and ``given_server`` (ITL-1267), mocked connection. The values a live server reports are asserted by the postgres-marked tests in ``tests/test_core/sources/test_postgresql_table_source_integration.py``. @@ -352,79 +352,203 @@ def test_current_location_reports_the_connection( assert connector.current_location() == (host, port, "testdb", "public") connector._conn = None + @pytest.fixture + def no_server_env(self, monkeypatch: pytest.MonkeyPatch) -> None: + for envvar in ("PGHOST", "PGHOSTADDR"): + monkeypatch.delenv(envvar, raising=False) + + # What psycopg's connection reports for a host of the DSN or the environment: + # psycopg resolves the host itself and passes the address it reached as + # ``hostaddr``, which is never the user's. + RESOLVED = {"host": "db.example.org", "hostaddr": "203.0.113.9"} + @pytest.mark.parametrize( - "dsn", + ("dsn", "expected"), [ - "host=a.example.org,b.example.org port=5432 dbname=x", - "host=a.example.org,b.example.org port=5432,5433 dbname=x", - "postgresql://u:p@a.example.org:5432,b.example.org:5433/x", - "postgresql://u@b.example.org,a.example.org/x", - "hostaddr=192.0.2.1,192.0.2.2 dbname=x", + ("host=db.example.org port=5432 dbname=x", ("db.example.org", "")), + ("postgresql://u:p@db.example.org:5432/x", ("db.example.org", "")), + ("host=/var/run/postgresql dbname=x", ("/var/run/postgresql", "")), + # A host beside a hostaddr, in both orders, in both DSN forms. + ( + "host=db.example.org hostaddr=192.0.2.1 dbname=x", + ("db.example.org", "192.0.2.1"), + ), + ( + "hostaddr=192.0.2.1 dbname=x host=db.example.org", + ("db.example.org", "192.0.2.1"), + ), + ( + "postgresql://u@db.example.org/x?hostaddr=192.0.2.1", + ("db.example.org", "192.0.2.1"), + ), + ( + "postgresql:///x?hostaddr=192.0.2.1&host=db.example.org", + ("db.example.org", "192.0.2.1"), + ), + # Several servers, in both DSN forms and both orders. + ( + "host=a.example.org,b.example.org port=5432 dbname=x", + ("a.example.org,b.example.org", ""), + ), + ( + "postgresql://u:p@b.example.org:5433,a.example.org:5432/x", + ("b.example.org,a.example.org", ""), + ), + ( + "hostaddr=192.0.2.1,192.0.2.2 dbname=x", + ("", "192.0.2.1,192.0.2.2"), + ), ], ) - def test_several_hosts_in_the_dsn( - self, dsn: str, monkeypatch: pytest.MonkeyPatch + def test_given_in_the_dsn( + self, dsn: str, expected: tuple[str, str], no_server_env: None ) -> None: - monkeypatch.delenv("PGHOST", raising=False) - monkeypatch.delenv("PGHOSTADDR", raising=False) - connector = self._connector(dsn) - assert connector.names_several_servers() + reported = dict(self.RESOLVED) if expected[0] else {} + connector = self._connector(dsn, parameters=reported) + assert connector.given_server() == expected connector._conn = None + def test_hostaddr_alone(self, no_server_env: None) -> None: + # libpq then reports no host; the address is the server. + for dsn in ( + "hostaddr=192.0.2.1 dbname=x", + "postgresql:///x?hostaddr=192.0.2.1", + ): + connector = self._connector(dsn, parameters={"hostaddr": "192.0.2.1"}) + assert connector.given_server() == ("", "192.0.2.1") + connector._conn = None + @pytest.mark.parametrize( - ("envvar", "value"), + ("dsn", "env", "expected"), [ - ("PGHOST", "a.example.org,b.example.org"), - ("PGHOSTADDR", "192.0.2.1,192.0.2.2"), + ("dbname=x", {"PGHOST": "db.example.org"}, ("db.example.org", "")), + ("dbname=x", {"PGHOSTADDR": "192.0.2.1"}, ("", "192.0.2.1")), + ( + "dbname=x", + {"PGHOST": "db.example.org", "PGHOSTADDR": "192.0.2.1"}, + ("db.example.org", "192.0.2.1"), + ), + ( + "dbname=x", + {"PGHOSTADDR": "192.0.2.1", "PGHOST": "db.example.org"}, + ("db.example.org", "192.0.2.1"), + ), + # A host of the DSN beside a PGHOSTADDR, and the other way round. + ( + "host=db.example.org dbname=x", + {"PGHOSTADDR": "192.0.2.1"}, + ("db.example.org", "192.0.2.1"), + ), + ( + "hostaddr=192.0.2.1 dbname=x", + {"PGHOST": "db.example.org"}, + ("db.example.org", "192.0.2.1"), + ), + # The DSN overrides the environment, key by key. + ( + "host=db.example.org dbname=x", + {"PGHOST": "a.example.org,b.example.org"}, + ("db.example.org", ""), + ), + ( + "host=db.example.org hostaddr=192.0.2.1 dbname=x", + {"PGHOSTADDR": "192.0.2.7,192.0.2.8"}, + ("db.example.org", "192.0.2.1"), + ), + ( + "dbname=x", + {"PGHOST": "a.example.org,b.example.org"}, + ("a.example.org,b.example.org", ""), + ), + ( + "dbname=x", + {"PGHOSTADDR": "192.0.2.1,192.0.2.2"}, + ("", "192.0.2.1,192.0.2.2"), + ), ], ) - def test_several_hosts_from_the_environment( - self, envvar: str, value: str, monkeypatch: pytest.MonkeyPatch + def test_given_in_the_environment( + self, + dsn: str, + env: dict[str, str], + expected: tuple[str, str], + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, ) -> None: - monkeypatch.delenv("PGHOST", raising=False) - monkeypatch.delenv("PGHOSTADDR", raising=False) - monkeypatch.setenv(envvar, value) - connector = self._connector("dbname=x user=u") - assert connector.names_several_servers() - connector._conn = None - - def test_the_dsn_host_overrides_the_environment( - self, monkeypatch: pytest.MonkeyPatch - ) -> None: - monkeypatch.setenv("PGHOST", "a.example.org,b.example.org") - monkeypatch.delenv("PGHOSTADDR", raising=False) - connector = self._connector("host=db.example.org dbname=x") - assert not connector.names_several_servers() - connector._conn = None - - @pytest.mark.parametrize("key", ["host", "hostaddr"]) - def test_several_hosts_the_connection_reports( - self, key: str, monkeypatch: pytest.MonkeyPatch - ) -> None: - # A service file can name several hosts; the DSN then names none, and only - # the connection's own parameters show them. - monkeypatch.delenv("PGHOST", raising=False) - monkeypatch.delenv("PGHOSTADDR", raising=False) - connector = self._connector( - "service=pool dbname=x", - parameters={key: "a.example.org,b.example.org"}, - ) - assert connector.names_several_servers() + for envvar, value in env.items(): + monkeypatch.setenv(envvar, value) + reported = dict(self.RESOLVED) if expected[0] else {"hostaddr": expected[1]} + connector = self._connector(dsn, parameters=reported) + assert connector.given_server() == expected connector._conn = None @pytest.mark.parametrize( - "dsn", + ("dsn", "env", "reported", "expected"), [ - "postgresql://u:p@db.example.org:5432/x", - "host=db.example.org port=5432 dbname=x", - "host=db.example.org hostaddr=192.0.2.1 dbname=x", - "host=/var/run/postgresql dbname=x", - "dbname=x", + # A service file gives the host: only the connection reports it. + ( + "service=pool dbname=x", + {}, + {"host": "db.example.org"}, + ("db.example.org", ""), + ), + ( + "service=pool dbname=x", + {}, + {"host": "db.example.org", "hostaddr": "192.0.2.1"}, + ("db.example.org", "192.0.2.1"), + ), + ( + "service=pool dbname=x", + {}, + {"hostaddr": "192.0.2.1", "host": "db.example.org"}, + ("db.example.org", "192.0.2.1"), + ), + ( + "service=pool dbname=x", + {}, + {"host": "a.example.org,b.example.org"}, + ("a.example.org,b.example.org", ""), + ), + ( + "service=pool dbname=x", + {}, + {"hostaddr": "192.0.2.1,192.0.2.2"}, + ("", "192.0.2.1,192.0.2.2"), + ), + # The service file's host beside a hostaddr of the DSN or the environment. + ( + "service=pool hostaddr=192.0.2.1 dbname=x", + {}, + {"host": "db.example.org", "hostaddr": "192.0.2.1"}, + ("db.example.org", "192.0.2.1"), + ), + ( + "service=pool dbname=x", + {"PGHOSTADDR": "192.0.2.1"}, + {"host": "db.example.org", "hostaddr": "192.0.2.1"}, + ("db.example.org", "192.0.2.1"), + ), + # A host of the DSN: the reported hostaddr is psycopg's, not the user's. + ( + "service=pool host=db.example.org dbname=x", + {}, + {"host": "db.example.org", "hostaddr": "203.0.113.9"}, + ("db.example.org", ""), + ), ], ) - def test_one_server(self, dsn: str, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.delenv("PGHOST", raising=False) - monkeypatch.delenv("PGHOSTADDR", raising=False) - connector = self._connector(dsn, parameters={"host": "db.example.org"}) - assert not connector.names_several_servers() + def test_given_in_a_service_file( + self, + dsn: str, + env: dict[str, str], + reported: dict[str, str], + expected: tuple[str, str], + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + for envvar, value in env.items(): + monkeypatch.setenv(envvar, value) + connector = self._connector(dsn, parameters=reported) + assert connector.given_server() == expected connector._conn = None From 713e2c9ce17f8b04723ee9e12e37b4c02830c1a5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 19:44:21 -0800 Subject: [PATCH 3/7] fix(sources): the PostgreSQL host and hostaddr are the ones libpq takes, service file included (ITL-1267) given_server now reads the host and hostaddr the connection reports (libpq takes each from the DSN, else a service file, else the environment) and drops only the address psycopg resolved for the reported host. This refuses a default id for a socket directory beside a service file's hostaddr and for a service file's host that overrode a PGHOST psycopg resolved. The unit tests hand psycopg's own connection attempt to libpq's PQconnectStart (nothing listening), in two orders. Docs: the hostaddr restriction applies when the two differ; an omitted port is the effective one. The omitted-port live test needs the localhost server. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1267.md | 9 +- docs/concepts/sources.md | 6 +- docs/reference/hashing.md | 13 +- src/orcapod/databases/postgresql_connector.py | 55 ++-- ...est_postgresql_table_source_integration.py | 56 ++++ .../test_postgresql_connector.py | 297 ++++++++++++------ 6 files changed, 304 insertions(+), 132 deletions(-) diff --git a/changelog.d/ITL-1267.md b/changelog.d/ITL-1267.md index ee71e5373..febb551b9 100644 --- a/changelog.d/ITL-1267.md +++ b/changelog.d/ITL-1267.md @@ -5,15 +5,16 @@ `postgresql_table:..
`), so one database, schema and table name on two servers gives two ids. The host is the name or address as libpq reports it, a host name in lower case, an IPv6 address in brackets in its exploded form (no `::`), a Unix-domain - socket directory as given; the port is always the number used, the default `5432` included. + socket directory as given; the port is always the number used (without one in the DSN, a + service file's, else `PGPORT`, else libpq's compiled default, normally `5432`). No user name, password or other connection parameter enters the id. The system-tag values and source-info tokens of rows read from PostgreSQL without a `source_id` change with it; a `source_id` you give is used as before, and a saved job keeps the id it was saved with. - A PostgreSQL source whose DSN, `PGHOST` / `PGHOSTADDR` setting or service file names several servers (`host=a,b`) has no default source id and raises `ValueError` unless it is given a `source_id`: the server reached can change from one connection to the next. So does one - whose parameters give a host beside a `hostaddr` that is not that address - (`host=db.example.org hostaddr=192.0.2.1`): the connection is sent to the address, so the - host name does not name the server. A `hostaddr` given alone names the server by that + whose parameters give a host beside a different `hostaddr` (`host=db.example.org + hostaddr=192.0.2.1`), each from the DSN, a service file or the environment, as libpq takes + them: the connection is sent to the address, so the host name does not name the server. A `hostaddr` given alone names the server by that address. A database, schema or table name holding `/` has no default either, as one holding `.` already had. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index cb395f666..8553e3717 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -41,8 +41,10 @@ where it lives (`sqlite_table::main.
`, reached; the [hashing reference](../reference/hashing.md#default-source-ids-and-row-identifiers) has every form). A PostgreSQL DSN that names several servers (`host=a,b`), or gives a host -beside a `hostaddr` (`host=db.example.org hostaddr=192.0.2.1`), has no default: give such a -source a `source_id`. `DBTableSource`, the base they share, can also be used directly +beside a different `hostaddr` (`host=db.example.org hostaddr=192.0.2.1`; with +`host=127.0.0.1 hostaddr=127.0.0.1` the default stays), has no default; the same holds when +`PGHOST`, `PGHOSTADDR` or a service file gives either value. Give such a source a +`source_id`. `DBTableSource`, the base they share, can also be used directly over any connector; a connector gives no address of its database, so it then has no default and needs a `source_id`. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index d1a9e22f6..f896b1434 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -191,13 +191,18 @@ never the address a name resolved to. A `hostaddr` given alone is the host. A host name is written in lower case (`DB.Example.ORG` and `db.example.org` are one id); an IPv6 address in brackets and in its exploded form, which holds no `::` (`[0000:0000:0000:0000:0000:0000:0000:0001]` for `::1`); an IPv4 address and a socket -directory as given. The port is always the number used, the default `5432` included, so a -DSN with `port=5432` and one without it give one id. Two spellings of one server are two +directory as given. The port is always the number used: a DSN without one uses the port of +a service file, else `PGPORT`, else libpq's compiled default (normally `5432`), so a DSN that +gives the port the connection would use anyway and one without it give one id. Two spellings of one server are two ids (`localhost` and `127.0.0.1`), as two spellings of one CSV path are. A DSN, a `PGHOST` or `PGHOSTADDR` setting or a service file that names several servers (`host=a,b`) gives no default: the server reached can change from one connection to the next. Neither do -parameters that give a host beside a `hostaddr` that is not that address -(`host=db.example.org hostaddr=192.0.2.1`): libpq sends the connection to the address, so +parameters that give a host beside a different `hostaddr` (`host=db.example.org +hostaddr=192.0.2.1`; `host=127.0.0.1 hostaddr=127.0.0.1` keeps a default), wherever each +comes from: libpq takes each parameter from the DSN, else a service file, else the +environment, so a service file's `hostaddr` counts beside a host of the DSN or `PGHOST`, and a +service file's host beside a `PGHOST` that psycopg resolved. libpq sends the connection to the +address, so the host name does not name the server, and two such DSNs with one host and two addresses would share an id. A name that DNS, a hosts file or a tunnel sends to another server is not seen in the parameters: two servers reached under one name that way share a default id and diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index 6f88248bd..f2d6ee675 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -412,8 +412,9 @@ def current_location(self) -> tuple[str, int, str, str]: connection (``PQhost``, ``PQport``): the host name or IP address as given (with ``host`` and ``hostaddr`` both given, the host; ``given_server`` tells that case apart), or the directory of a Unix-domain socket; the port is the - one used, the compiled default when none was given. Never the resolved address, the user, the password or any other - connection parameter (ITL-1267). + one used (when the DSN gives none, a service file's, else ``PGPORT``, else + libpq's compiled default). Never the resolved address, the user, the password + or any other connection parameter (ITL-1267). Returns: The host, the port, the database and the schema. @@ -432,20 +433,25 @@ def current_location(self) -> tuple[str, int, str, str]: return str(host), int(port), str(row[0]), str(row[1]) def given_server(self) -> tuple[str, str]: - """Return the ``host`` and ``hostaddr`` the user gave the connection. - - Each is read from the DSN, else from ``PGHOST`` / ``PGHOSTADDR``; when - neither names a host, libpq takes the host (and a ``hostaddr`` the DSN and - the environment do not give) from a service file, which only the parameters - the connection reports show. Never the parameters psycopg adds: psycopg - resolves a host of the DSN or the environment itself and passes the address - it reached as ``hostaddr``, so a reported ``hostaddr`` is the user's only when - no host came from the DSN or the environment. A value may be a - comma-separated list (``host=a,b``, ``postgresql://a:5432,b:5433/db``): libpq - then connects to the first server that answers. + """Return the ``host`` and the user's ``hostaddr`` of the connection. + + libpq takes each parameter from the DSN, else from a service file, else from + the environment (``PGHOST``, ``PGHOSTADDR``); the connection reports what it + took (its parameters), so the host and the address returned are the ones the + connection used, wherever they came from. One address is not the user's: + psycopg resolves a single host of the DSN or the environment itself (not a + Unix-socket directory, and only when neither gives a ``hostaddr``) and passes + the address it reached as ``hostaddr``, which overrides a service file's. + That address is dropped (``""``) when the host the connection reports is the + host psycopg resolved; when a service file's host overrode the environment's, + the connection was sent to the environment host's address, which is + returned. A value may be a comma-separated list (``host=a,b``, + ``postgresql://a:5432,b:5433/db``): libpq then connects to the first server + that answers. psycopg splits such a list of the DSN or the environment into + one attempt per server, so that list is returned as given. Returns: - The host and the host address as given, each ``""`` when none is. + The host and the host address, each ``""`` when there is none. """ from psycopg.conninfo import conninfo_to_dict @@ -455,12 +461,21 @@ def supplied(key: str, envvar: str) -> str: return str((given[key] if key in given else os.environ.get(envvar)) or "") host, hostaddr = supplied("host", "PGHOST"), supplied("hostaddr", "PGHOSTADDR") - if not host: - with self._lock: - reported = self._require_open().info.get_parameters() - host = reported.get("host", "") - hostaddr = hostaddr or reported.get("hostaddr", "") - return host, hostaddr + if "," in host or "," in hostaddr: + return host, hostaddr + with self._lock: + reported = self._require_open().info.get_parameters() + used_host = str(reported.get("host", "")) + used_hostaddr = str(reported.get("hostaddr", "")) + resolved_by_psycopg = ( + bool(host) + and not hostaddr + and not host.startswith("/") + and host[1:2] != ":" # a Windows socket directory, as psycopg tests it + ) + if resolved_by_psycopg and used_host == host: + used_hostaddr = "" + return used_host, used_hostaddr def get_pk_columns(self, table_name: str) -> list[str]: """Return primary-key column names in key-sequence order.""" diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index 2d6b9fbd5..d21277061 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -373,6 +373,7 @@ def test_upper_case_host_name_gives_the_lower_case_id( def test_omitted_port_is_written_as_the_port_used( self, server_table: str, no_server_env: None ) -> None: + _requires_localhost() if _SERVER["port"] != "5432": pytest.skip("needs the test server on the default port 5432") omitted = _source_id(_keyword_dsn(server_table, host="localhost", port=None)) @@ -490,6 +491,61 @@ def test_host_beside_hostaddr_from_a_service_file_has_no_default( with pytest.raises(ValueError, match="host name alone does not identify"): _source_id(dsn) + @pytest.mark.parametrize( + ("dsn_host", "env_host"), + [("localhost", None), (None, "localhost")], + ids=["dsn-host", "pghost"], + ) + def test_host_name_beside_a_service_file_hostaddr_keeps_the_default( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + tmp_path, + dsn_host: str | None, + env_host: str | None, + ) -> None: + # psycopg resolves a host name of the DSN or PGHOST and passes the address it + # reached as hostaddr, which overrides the service file's: the connection goes + # to the named host, not to the service file's unreachable address (a wrong + # claim would fail at connect_timeout). + _requires_localhost() + service_file = tmp_path / "pg_service.conf" + service_file.write_text(f"[one]\nhostaddr=192.0.2.1\nport={_SERVER['port']}\n") + monkeypatch.setenv("PGSERVICEFILE", str(service_file)) + if env_host is not None: + monkeypatch.setenv("PGHOST", env_host) + dsn = _keyword_dsn( + server_table, host=dsn_host, port=None, service="one", connect_timeout="5" + ) + assert _source_id(dsn) == _expected("localhost", server_table) + + @pytest.mark.parametrize( + ("service_host", "env_host"), + [("localhost", "127.0.0.1"), ("127.0.0.1", "localhost")], + ids=["service-name-env-address", "service-address-env-name"], + ) + def test_service_file_host_beside_a_resolved_pghost_has_no_default( + self, + server_table: str, + no_server_env: None, + monkeypatch: pytest.MonkeyPatch, + tmp_path, + service_host: str, + env_host: str, + ) -> None: + # libpq takes the service file's host over PGHOST, while psycopg resolved + # PGHOST and sent the connection to that address: the reported host does not + # name the server reached. + _requires_localhost() + service_file = tmp_path / "pg_service.conf" + service_file.write_text(f"[one]\nhost={service_host}\nport={_SERVER['port']}\n") + monkeypatch.setenv("PGSERVICEFILE", str(service_file)) + monkeypatch.setenv("PGHOST", env_host) + dsn = _keyword_dsn(server_table, host=None, port=None, service="one") + with pytest.raises(ValueError, match="host name alone does not identify"): + _source_id(dsn) + def test_host_from_a_service_file_names_the_host( self, server_table: str, diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index c83d4b7aa..28324b669 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -3,6 +3,8 @@ from __future__ import annotations +import pathlib +import socket from unittest.mock import MagicMock, patch import pyarrow as pa @@ -352,31 +354,119 @@ def test_current_location_reports_the_connection( assert connector.current_location() == (host, port, "testdb", "public") connector._conn = None + # ── given_server: what libpq takes, from the DSN, a service file, the environment + # + # Each case hands psycopg's own first connection attempt for the DSN (its host + # resolution included, every host name resolving to PSYCOPG_ADDRESS) to libpq's + # PQconnectStart, which applies the DSN, then the service file, then the + # environment, before it connects; nothing listens at any address used, and the + # attempt is abandoned once its parameters are read. So the precedence tested is + # libpq's own, not a model of it. + + PSYCOPG_ADDRESS = "203.0.113.9" + SOCKET = "/var/run/postgresql" + SERVER_ENV = ("PGHOST", "PGHOSTADDR", "PGSERVICE", "PGSERVICEFILE", "PGSYSCONFDIR") + @pytest.fixture - def no_server_env(self, monkeypatch: pytest.MonkeyPatch) -> None: - for envvar in ("PGHOST", "PGHOSTADDR"): + def isolated_env( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path + ) -> pathlib.Path: + """No server variable of the caller's; no service file but the test's.""" + for envvar in self.SERVER_ENV: monkeypatch.delenv(envvar, raising=False) + monkeypatch.setenv("PGSYSCONFDIR", str(tmp_path)) + monkeypatch.setenv("PGSERVICEFILE", str(tmp_path / "pg_service.conf")) + return tmp_path + + def _as_libpq_takes(self, dsn: str) -> PostgreSQLConnector: + """A connector whose connection reports the parameters libpq takes for dsn.""" + from psycopg import pq + from psycopg.conninfo import conninfo_attempts, conninfo_to_dict, make_conninfo + + resolved = [ + (socket.AF_INET, socket.SOCK_STREAM, 6, "", (self.PSYCOPG_ADDRESS, 5432)) + ] + with patch("socket.getaddrinfo", return_value=resolved): + attempt = conninfo_attempts(conninfo_to_dict(dsn))[0] + pgconn = pq.PGconn.connect_start(make_conninfo("", **attempt).encode()) + try: + reported = { + option.keyword.decode(): option.val.decode() + for option in pgconn.info + if option.val and option.keyword in (b"host", b"hostaddr") + } + finally: + pgconn.finish() + return self._connector(dsn, parameters=reported) - # What psycopg's connection reports for a host of the DSN or the environment: - # psycopg resolves the host itself and passes the address it reached as - # ``hostaddr``, which is never the user's. - RESOLVED = {"host": "db.example.org", "hostaddr": "203.0.113.9"} + def _given( + self, + isolated_env: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + dsn: list[str], + env: dict[str, str], + service: list[str] | None, + reverse: bool, + ) -> tuple[str, str]: + """``given_server`` for the DSN keywords, environment and service file lines. + + ``reverse`` writes the DSN keywords, the variables and the service file lines + in the other order. + """ + + def ordered(items: list[str]) -> list[str]: + return items[::-1] if reverse else items + + if service is not None: + lines = ordered(service) + (isolated_env / "pg_service.conf").write_text( + "\n".join(["[one]", *lines]) + "\n" + ) + dsn = [*dsn, "service=one"] + for envvar in ordered(list(env)): + monkeypatch.setenv(envvar, env[envvar]) + connector = self._as_libpq_takes(" ".join(ordered([*dsn, "dbname=x"]))) + try: + return connector.given_server() + finally: + connector._conn = None + @pytest.mark.parametrize("reverse", [False, True], ids=["in-order", "reversed"]) @pytest.mark.parametrize( ("dsn", "expected"), [ - ("host=db.example.org port=5432 dbname=x", ("db.example.org", "")), - ("postgresql://u:p@db.example.org:5432/x", ("db.example.org", "")), - ("host=/var/run/postgresql dbname=x", ("/var/run/postgresql", "")), - # A host beside a hostaddr, in both orders, in both DSN forms. + (["host=db.example.org"], ("db.example.org", "")), + ([f"host={SOCKET}"], (SOCKET, "")), + (["host=192.0.2.1"], ("192.0.2.1", "")), + (["hostaddr=192.0.2.1"], ("", "192.0.2.1")), + (["host=192.0.2.1", "hostaddr=192.0.2.1"], ("192.0.2.1", "192.0.2.1")), ( - "host=db.example.org hostaddr=192.0.2.1 dbname=x", + ["host=db.example.org", "hostaddr=192.0.2.1"], ("db.example.org", "192.0.2.1"), ), + ([f"host={SOCKET}", "hostaddr=192.0.2.1"], (SOCKET, "192.0.2.1")), ( - "hostaddr=192.0.2.1 dbname=x host=db.example.org", - ("db.example.org", "192.0.2.1"), + ["host=a.example.org,b.example.org", "port=5432"], + ("a.example.org,b.example.org", ""), ), + (["hostaddr=192.0.2.1,192.0.2.2"], ("", "192.0.2.1,192.0.2.2")), + ], + ) + def test_given_in_the_dsn( + self, + isolated_env: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + dsn: list[str], + expected: tuple[str, str], + reverse: bool, + ) -> None: + given = self._given(isolated_env, monkeypatch, dsn, {}, None, reverse) + assert given == expected + + @pytest.mark.parametrize( + ("dsn", "expected"), + [ + ("postgresql://u:p@db.example.org:5432/x", ("db.example.org", "")), ( "postgresql://u@db.example.org/x?hostaddr=192.0.2.1", ("db.example.org", "192.0.2.1"), @@ -385,170 +475,173 @@ def no_server_env(self, monkeypatch: pytest.MonkeyPatch) -> None: "postgresql:///x?hostaddr=192.0.2.1&host=db.example.org", ("db.example.org", "192.0.2.1"), ), - # Several servers, in both DSN forms and both orders. - ( - "host=a.example.org,b.example.org port=5432 dbname=x", - ("a.example.org,b.example.org", ""), - ), ( "postgresql://u:p@b.example.org:5433,a.example.org:5432/x", ("b.example.org,a.example.org", ""), ), - ( - "hostaddr=192.0.2.1,192.0.2.2 dbname=x", - ("", "192.0.2.1,192.0.2.2"), - ), + ("postgresql:///x?hostaddr=192.0.2.1", ("", "192.0.2.1")), ], ) - def test_given_in_the_dsn( - self, dsn: str, expected: tuple[str, str], no_server_env: None + def test_given_in_a_uri( + self, isolated_env: pathlib.Path, dsn: str, expected: tuple[str, str] ) -> None: - reported = dict(self.RESOLVED) if expected[0] else {} - connector = self._connector(dsn, parameters=reported) + connector = self._as_libpq_takes(dsn) assert connector.given_server() == expected connector._conn = None - def test_hostaddr_alone(self, no_server_env: None) -> None: - # libpq then reports no host; the address is the server. - for dsn in ( - "hostaddr=192.0.2.1 dbname=x", - "postgresql:///x?hostaddr=192.0.2.1", - ): - connector = self._connector(dsn, parameters={"hostaddr": "192.0.2.1"}) - assert connector.given_server() == ("", "192.0.2.1") - connector._conn = None - + @pytest.mark.parametrize("reverse", [False, True], ids=["in-order", "reversed"]) @pytest.mark.parametrize( ("dsn", "env", "expected"), [ - ("dbname=x", {"PGHOST": "db.example.org"}, ("db.example.org", "")), - ("dbname=x", {"PGHOSTADDR": "192.0.2.1"}, ("", "192.0.2.1")), + ([], {"PGHOST": "db.example.org"}, ("db.example.org", "")), + ([], {"PGHOSTADDR": "192.0.2.1"}, ("", "192.0.2.1")), ( - "dbname=x", + [], {"PGHOST": "db.example.org", "PGHOSTADDR": "192.0.2.1"}, ("db.example.org", "192.0.2.1"), ), ( - "dbname=x", - {"PGHOSTADDR": "192.0.2.1", "PGHOST": "db.example.org"}, - ("db.example.org", "192.0.2.1"), - ), - # A host of the DSN beside a PGHOSTADDR, and the other way round. - ( - "host=db.example.org dbname=x", + ["host=db.example.org"], {"PGHOSTADDR": "192.0.2.1"}, ("db.example.org", "192.0.2.1"), ), ( - "hostaddr=192.0.2.1 dbname=x", + ["hostaddr=192.0.2.1"], {"PGHOST": "db.example.org"}, ("db.example.org", "192.0.2.1"), ), + ([], {"PGHOST": SOCKET, "PGHOSTADDR": "192.0.2.1"}, (SOCKET, "192.0.2.1")), # The DSN overrides the environment, key by key. ( - "host=db.example.org dbname=x", + ["host=db.example.org"], {"PGHOST": "a.example.org,b.example.org"}, ("db.example.org", ""), ), ( - "host=db.example.org hostaddr=192.0.2.1 dbname=x", + ["host=db.example.org", "hostaddr=192.0.2.1"], {"PGHOSTADDR": "192.0.2.7,192.0.2.8"}, ("db.example.org", "192.0.2.1"), ), ( - "dbname=x", + [], {"PGHOST": "a.example.org,b.example.org"}, ("a.example.org,b.example.org", ""), ), - ( - "dbname=x", - {"PGHOSTADDR": "192.0.2.1,192.0.2.2"}, - ("", "192.0.2.1,192.0.2.2"), - ), + ([], {"PGHOSTADDR": "192.0.2.1,192.0.2.2"}, ("", "192.0.2.1,192.0.2.2")), ], ) def test_given_in_the_environment( self, - dsn: str, + isolated_env: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + dsn: list[str], env: dict[str, str], expected: tuple[str, str], - no_server_env: None, - monkeypatch: pytest.MonkeyPatch, + reverse: bool, ) -> None: - for envvar, value in env.items(): - monkeypatch.setenv(envvar, value) - reported = dict(self.RESOLVED) if expected[0] else {"hostaddr": expected[1]} - connector = self._connector(dsn, parameters=reported) - assert connector.given_server() == expected - connector._conn = None + given = self._given(isolated_env, monkeypatch, dsn, env, None, reverse) + assert given == expected + @pytest.mark.parametrize("reverse", [False, True], ids=["in-order", "reversed"]) @pytest.mark.parametrize( - ("dsn", "env", "reported", "expected"), + ("service", "dsn", "env", "expected"), [ - # A service file gives the host: only the connection reports it. + # Host and address from the service file alone. + (["host=svc.invalid"], [], {}, ("svc.invalid", "")), ( - "service=pool dbname=x", + ["host=svc.invalid", "hostaddr=192.0.2.50"], + [], {}, - {"host": "db.example.org"}, - ("db.example.org", ""), + ("svc.invalid", "192.0.2.50"), ), ( - "service=pool dbname=x", + ["host=192.0.2.50", "hostaddr=192.0.2.50"], + [], {}, - {"host": "db.example.org", "hostaddr": "192.0.2.1"}, - ("db.example.org", "192.0.2.1"), + ("192.0.2.50", "192.0.2.50"), ), + (["hostaddr=192.0.2.50"], [], {}, ("", "192.0.2.50")), ( - "service=pool dbname=x", + ["host=a.invalid,b.invalid"], + [], {}, - {"hostaddr": "192.0.2.1", "host": "db.example.org"}, - ("db.example.org", "192.0.2.1"), + ("a.invalid,b.invalid", ""), ), + # The service file's address beside a host of the DSN or the environment: + # psycopg resolves a host name and passes its address, which overrides the + # service file's; it does not resolve a socket directory, so the service + # file's address is the one used. ( - "service=pool dbname=x", + ["hostaddr=192.0.2.50"], + ["host=db.example.org"], {}, - {"host": "a.example.org,b.example.org"}, - ("a.example.org,b.example.org", ""), + ("db.example.org", ""), ), + (["hostaddr=192.0.2.50"], [f"host={SOCKET}"], {}, (SOCKET, "192.0.2.50")), ( - "service=pool dbname=x", - {}, - {"hostaddr": "192.0.2.1,192.0.2.2"}, - ("", "192.0.2.1,192.0.2.2"), + ["hostaddr=192.0.2.50"], + [], + {"PGHOST": "db.example.org"}, + ("db.example.org", ""), + ), + (["hostaddr=192.0.2.50"], [], {"PGHOST": SOCKET}, (SOCKET, "192.0.2.50")), + # The service file overrides the environment, key by key. + ( + ["hostaddr=192.0.2.50"], + [], + {"PGHOSTADDR": "192.0.2.60"}, + ("", "192.0.2.50"), + ), + ( + ["host=svc.invalid"], + [], + {"PGHOST": "db.example.org"}, + ("svc.invalid", PSYCOPG_ADDRESS), ), - # The service file's host beside a hostaddr of the DSN or the environment. + (["host=svc.invalid"], [], {"PGHOST": SOCKET}, ("svc.invalid", "")), ( - "service=pool hostaddr=192.0.2.1 dbname=x", + ["host=svc.invalid"], + [], + {"PGHOST": "db.example.org", "PGHOSTADDR": "192.0.2.60"}, + ("svc.invalid", "192.0.2.60"), + ), + # The service file's host beside an address of the DSN or the environment. + ( + ["host=svc.invalid"], + ["hostaddr=192.0.2.1"], {}, - {"host": "db.example.org", "hostaddr": "192.0.2.1"}, - ("db.example.org", "192.0.2.1"), + ("svc.invalid", "192.0.2.1"), ), ( - "service=pool dbname=x", - {"PGHOSTADDR": "192.0.2.1"}, - {"host": "db.example.org", "hostaddr": "192.0.2.1"}, - ("db.example.org", "192.0.2.1"), + ["host=svc.invalid"], + [], + {"PGHOSTADDR": "192.0.2.60"}, + ("svc.invalid", "192.0.2.60"), ), - # A host of the DSN: the reported hostaddr is psycopg's, not the user's. + # The DSN overrides the service file. ( - "service=pool host=db.example.org dbname=x", + ["host=svc.invalid", "hostaddr=192.0.2.50"], + ["host=db.example.org"], {}, - {"host": "db.example.org", "hostaddr": "203.0.113.9"}, ("db.example.org", ""), ), + ( + ["host=svc.invalid", "hostaddr=192.0.2.50"], + ["hostaddr=192.0.2.1"], + {}, + ("svc.invalid", "192.0.2.1"), + ), ], ) def test_given_in_a_service_file( self, - dsn: str, + isolated_env: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + service: list[str], + dsn: list[str], env: dict[str, str], - reported: dict[str, str], expected: tuple[str, str], - no_server_env: None, - monkeypatch: pytest.MonkeyPatch, + reverse: bool, ) -> None: - for envvar, value in env.items(): - monkeypatch.setenv(envvar, value) - connector = self._connector(dsn, parameters=reported) - assert connector.given_server() == expected - connector._conn = None + given = self._given(isolated_env, monkeypatch, dsn, env, service, reverse) + assert given == expected From 067823976d276617950da916d3e94aa7f85e238d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 20:44:08 -0800 Subject: [PATCH 4/7] fix(sources): read PGHOST/PGHOSTADDR when the PostgreSQL connector connects; pin psycopg's host resolution (ITL-1267) given_server decided from PGHOST / PGHOSTADDR read at call time whether the reported hostaddr was psycopg's resolution and whether several servers were named; the connector now takes them immediately before psycopg.connect, so a later change of the environment changes nothing (tested by changing it after construction). A new test class pins the psycopg behaviour given_server relies on (Connection.connect resolves a single host name and passes it as hostaddr; an address or a socket directory passes as given), through psycopg's own connect loop and real resolution of localhost; the docstring names it. The hashing reference states the measured service-file rule: beside a host name of the DSN or PGHOST, a service file's hostaddr changes nothing. Co-Authored-By: Claude Opus 5.5 --- docs/reference/hashing.md | 13 +- src/orcapod/databases/postgresql_connector.py | 41 ++++-- .../test_postgresql_connector.py | 127 ++++++++++++++++++ 3 files changed, 169 insertions(+), 12 deletions(-) diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index f499152f6..426797abe 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -203,10 +203,15 @@ or `PGHOSTADDR` setting or a service file that names several servers (`host=a,b` default: the server reached can change from one connection to the next. Neither do parameters that give a host beside a different `hostaddr` (`host=db.example.org hostaddr=192.0.2.1`; `host=127.0.0.1 hostaddr=127.0.0.1` keeps a default), wherever each -comes from: libpq takes each parameter from the DSN, else a service file, else the -environment, so a service file's `hostaddr` counts beside a host of the DSN or `PGHOST`, and a -service file's host beside a `PGHOST` that psycopg resolved. libpq sends the connection to the -address, so +comes from. libpq takes each parameter from the DSN, else a service file, else the +environment; psycopg resolves a single host name of the DSN or `PGHOST` itself, when neither +gives a `hostaddr`, and passes the address it reached as `hostaddr`, which overrides a service +file's. So a service file's `hostaddr` beside a host name of the DSN or `PGHOST` changes +nothing (the connection goes to the named host, and the default stays), while beside a +Unix-socket directory, which psycopg does not resolve, it is the address used and there is no +default; and a service file's host beside a `PGHOST` that psycopg resolved has no default +(libpq reports the service file's host, the connection went to the `PGHOST` address). libpq +sends the connection to the address, so the host name does not name the server, and two such DSNs with one host and two addresses would share an id. A name that DNS, a hosts file or a tunnel sends to another server is not seen in the parameters: two servers reached under one name that way share a default id and diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index f2d6ee675..cd59c4dc4 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -344,6 +344,23 @@ def _field_has_metadata(field: pa.Field) -> bool: return False +def _psycopg_server(dsn: str) -> tuple[str, str]: + """Return the ``host`` and ``hostaddr`` psycopg reads for ``dsn``, now. + + Each from the DSN, else from ``PGHOST`` / ``PGHOSTADDR`` (a service file is + libpq's, and psycopg does not read it), ``""`` when neither gives one. psycopg + decides from these whether it resolves the host itself. + """ + from psycopg.conninfo import conninfo_to_dict + + given = conninfo_to_dict(dsn) + + def supplied(key: str, envvar: str) -> str: + return str((given[key] if key in given else os.environ.get(envvar)) or "") + + return supplied("host", "PGHOST"), supplied("hostaddr", "PGHOSTADDR") + + # --------------------------------------------------------------------------- # PostgreSQLConnector # --------------------------------------------------------------------------- @@ -366,6 +383,10 @@ class PostgreSQLConnector: def __init__(self, dsn: str) -> None: self._dsn = dsn + # The host and hostaddr psycopg reads for this connection (the DSN, else + # PGHOST / PGHOSTADDR), taken when it connects: ``given_server`` must not + # read an environment changed since (ITL-1267). + self._psycopg_server = _psycopg_server(dsn) self._conn: Any = psycopg.connect(dsn, autocommit=False) self._lock = threading.RLock() # RLock required: iter_batches → _resolve_column_type_lookup → get_column_info re-enters the lock self._cursor_seq = itertools.count() @@ -450,17 +471,21 @@ def given_server(self) -> tuple[str, str]: that answers. psycopg splits such a list of the DSN or the environment into one attempt per server, so that list is returned as given. + This relies on one psycopg behaviour, that of ``Connection.connect`` in + psycopg 3.1.17 and later (earlier releases passed the DSN to libpq + unchanged): a single host name of the DSN or ``PGHOST``, with no + ``hostaddr`` there, is resolved by psycopg and passed to libpq as + ``hostaddr`` (``TestPsycopgResolvesTheHost`` pins it). + + What psycopg read from the DSN and the environment is taken when the + connector connected, so a later change of ``PGHOST`` or ``PGHOSTADDR`` + changes nothing here; the host and the address are what the connection + reports. + Returns: The host and the host address, each ``""`` when there is none. """ - from psycopg.conninfo import conninfo_to_dict - - given = conninfo_to_dict(self._dsn) - - def supplied(key: str, envvar: str) -> str: - return str((given[key] if key in given else os.environ.get(envvar)) or "") - - host, hostaddr = supplied("host", "PGHOST"), supplied("hostaddr", "PGHOSTADDR") + host, hostaddr = self._psycopg_server if "," in host or "," in hostaddr: return host, hostaddr with self._lock: diff --git a/tests/test_databases/test_postgresql_connector.py b/tests/test_databases/test_postgresql_connector.py index 28324b669..b73c7fcc2 100644 --- a/tests/test_databases/test_postgresql_connector.py +++ b/tests/test_databases/test_postgresql_connector.py @@ -5,8 +5,10 @@ import pathlib import socket +from typing import Any from unittest.mock import MagicMock, patch +import psycopg import pyarrow as pa import pytest @@ -645,3 +647,128 @@ def test_given_in_a_service_file( ) -> None: given = self._given(isolated_env, monkeypatch, dsn, env, service, reverse) assert given == expected + + @pytest.mark.parametrize( + ("at_connect", "later", "expected"), + [ + # psycopg resolved PGHOST: a PGHOSTADDR set later does not make its + # address the user's. + ( + {"PGHOST": "db.example.org"}, + {"PGHOSTADDR": "192.0.2.7"}, + ("db.example.org", ""), + ), + # Another host later, in place of the one connected to. + ( + {"PGHOST": "db.example.org"}, + {"PGHOST": "other.example.org"}, + ("db.example.org", ""), + ), + # Several servers at connect time stay several when PGHOST is unset. + ( + {"PGHOST": "a.example.org,b.example.org"}, + {"PGHOST": None}, + ("a.example.org,b.example.org", ""), + ), + # One server at connect time stays one when PGHOST becomes a list. + ( + {"PGHOST": "db.example.org"}, + {"PGHOST": "a.example.org,b.example.org"}, + ("db.example.org", ""), + ), + ], + ) + def test_the_environment_is_read_when_the_connector_connects( + self, + isolated_env: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + at_connect: dict[str, str], + later: dict[str, str | None], + expected: tuple[str, str], + ) -> None: + for envvar, value in at_connect.items(): + monkeypatch.setenv(envvar, value) + connector = self._as_libpq_takes("dbname=x") + for envvar, value in later.items(): + if value is None: + monkeypatch.delenv(envvar) + else: + monkeypatch.setenv(envvar, value) + try: + assert connector.given_server() == expected + finally: + connector._conn = None + + +class TestPsycopgResolvesTheHost: + """The psycopg behaviour ``given_server`` relies on, pinned (ITL-1267). + + psycopg's ``Connection.connect`` resolves a single host name of the DSN or + ``PGHOST`` itself, when neither gives a ``hostaddr``, and passes the address to + libpq as ``hostaddr`` (psycopg 3.1.17 and later; earlier releases passed the DSN + unchanged). Real name resolution of ``localhost`` and psycopg's own connect + loop: only the step that would open the connection is replaced, to record the + connection string psycopg hands to libpq. If a future psycopg stops doing this + (or renames that step), these tests fail. + """ + + @staticmethod + def _passed_to_libpq(dsn: str) -> list[dict[str, Any]]: + from psycopg.conninfo import conninfo_to_dict + + passed: list[str] = [] + + def refuse(conninfo: str, **_: Any) -> Any: + passed.append(conninfo) + raise psycopg.OperationalError("not connecting in a unit test") + + with patch.object(psycopg.Connection, "_connect_gen", side_effect=refuse): + with pytest.raises(psycopg.OperationalError): + psycopg.connect(dsn) + assert passed, "psycopg did not reach the step that opens the connection" + return [conninfo_to_dict(conninfo) for conninfo in passed] + + @staticmethod + def _addresses(name: str) -> set[str]: + return { + str(info[4][0]) + for info in socket.getaddrinfo( + name, 5432, proto=socket.IPPROTO_TCP, type=socket.SOCK_STREAM + ) + } + + @pytest.fixture(autouse=True) + def _no_server_env(self, monkeypatch: pytest.MonkeyPatch) -> None: + for envvar in ("PGHOST", "PGHOSTADDR", "PGSERVICE"): + monkeypatch.delenv(envvar, raising=False) + + @pytest.mark.parametrize("via", ["dsn", "PGHOST"]) + def test_a_host_name_is_passed_with_the_address_psycopg_resolved( + self, monkeypatch: pytest.MonkeyPatch, via: str + ) -> None: + if via == "PGHOST": + monkeypatch.setenv("PGHOST", "localhost") + dsn = "host=localhost dbname=x" if via == "dsn" else "dbname=x" + attempts = self._passed_to_libpq(dsn) + addresses = self._addresses("localhost") + assert {attempt["hostaddr"] for attempt in attempts} <= addresses + assert all( + attempt.get("host", "localhost") == "localhost" for attempt in attempts + ) + + @pytest.mark.parametrize( + ("dsn", "hostaddr"), + [ + ("host=127.0.0.1 dbname=x", "127.0.0.1"), + ("host=localhost hostaddr=192.0.2.1 dbname=x", "192.0.2.1"), + ("hostaddr=192.0.2.1 host=localhost dbname=x", "192.0.2.1"), + ], + ) + def test_an_address_is_passed_as_given(self, dsn: str, hostaddr: str) -> None: + assert [attempt["hostaddr"] for attempt in self._passed_to_libpq(dsn)] == [ + hostaddr + ] + + def test_a_socket_directory_is_not_resolved(self) -> None: + attempts = self._passed_to_libpq("host=/var/run/postgresql dbname=x") + assert [attempt.get("hostaddr") for attempt in attempts] == [None] From 5f855f765f519c6dc852f115031a255b8cfa9fb2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 20:55:01 -0800 Subject: [PATCH 5/7] build(deps): psycopg 3.1.17 or later for orcapod[postgresql] (ITL-1267) The default PostgreSQL source id relies on psycopg's Connection.connect resolving a single host name of the DSN or PGHOST and passing the address as hostaddr (overriding a service file's), which psycopg does from 3.1.17 on (measured from the sdists: 3.0.x to 3.1.16 do not). The floor moves from 3.0 in the postgresql extra and the dev group; uv.lock keeps psycopg 3.3.3 and changes only its specifier lines. TestPsycopgResolvesTheHost pins the behaviour. README, the hashing reference and the changelog fragment state the reason. Developer approval, 2026-11-19. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- changelog.d/ITL-1267.md | 5 +++++ docs/reference/hashing.md | 3 ++- pyproject.toml | 4 ++-- uv.lock | 6 +++--- 5 files changed, 13 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 1f3b6d4b4..e2519ad40 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ Optional features are installed as extras, for example `uv add "orcapod[spiraldb |-------|------| | `orcapod[ray]` | Distributed execution with `RayExecutor` | | `orcapod[redis]` | `RedisCacher`, a Redis-backed hash cache | -| `orcapod[postgresql]` | The PostgreSQL connector, table source and file hash cache | +| `orcapod[postgresql]` | The PostgreSQL connector, table source and file hash cache (psycopg 3.1.17 or later) | | `orcapod[spiraldb]` | The SpiralDB connector and table source | | `orcapod[torch]` | PyTorch, for `torch.Tensor` values (any installed `torch` works) | | `orcapod[all]` | All of the above | diff --git a/changelog.d/ITL-1267.md b/changelog.d/ITL-1267.md index febb551b9..05b171573 100644 --- a/changelog.d/ITL-1267.md +++ b/changelog.d/ITL-1267.md @@ -18,3 +18,8 @@ them: the connection is sent to the address, so the host name does not name the server. A `hostaddr` given alone names the server by that address. A database, schema or table name holding `/` has no default either, as one holding `.` already had. +- `orcapod[postgresql]` requires psycopg 3.1.17 or later (was 3.0). The default PostgreSQL + source id relies on psycopg resolving a single host name of the DSN or `PGHOST` itself and + passing the address to libpq as `hostaddr`, which `Connection.connect` does from 3.1.17 + on; with an earlier psycopg, a service file's `hostaddr` beside a host name would be the + address used while the id named the host. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 426797abe..a683cecd7 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -204,7 +204,8 @@ default: the server reached can change from one connection to the next. Neither parameters that give a host beside a different `hostaddr` (`host=db.example.org hostaddr=192.0.2.1`; `host=127.0.0.1 hostaddr=127.0.0.1` keeps a default), wherever each comes from. libpq takes each parameter from the DSN, else a service file, else the -environment; psycopg resolves a single host name of the DSN or `PGHOST` itself, when neither +environment; psycopg (3.1.17 or later, the version `orcapod[postgresql]` requires for this) +resolves a single host name of the DSN or `PGHOST` itself, when neither gives a `hostaddr`, and passes the address it reached as `hostaddr`, which overrides a service file's. So a service file's `hostaddr` beside a host name of the DSN or `PGHOST` changes nothing (the connection goes to the named host, and the default stays), while beside a diff --git a/pyproject.toml b/pyproject.toml index 4011cecca..089125635 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,7 +44,7 @@ Issues = "https://github.com/metamorphic-labs/orcapod-python/issues" [project.optional-dependencies] redis = ["redis>=6.2.0"] ray = ["ray[default]==2.48.0", "ipywidgets>=8.1.7"] -postgresql = ["psycopg[binary]>=3.0"] +postgresql = ["psycopg[binary]>=3.1.17"] spiraldb = [ "pyspiral>=0.16.33", ] @@ -97,7 +97,7 @@ dev = [ "pytest-asyncio>=1.3.0", "pytest-cov>=6.1.1", "pytest-xdist>=3.6", - "psycopg[binary]>=3.0", + "psycopg[binary]>=3.1.17", "ray[default]==2.48.0", "redis>=6.2.0", "ruff>=0.14.4", diff --git a/uv.lock b/uv.lock index 17ad21c4a..ef85340f8 100644 --- a/uv.lock +++ b/uv.lock @@ -2132,8 +2132,8 @@ requires-dist = [ { name = "numpy", specifier = ">=1.26.4" }, { name = "pandas", specifier = ">=2.2.3,<3" }, { name = "polars", specifier = ">=1.36.0" }, - { name = "psycopg", extras = ["binary"], marker = "extra == 'all'", specifier = ">=3.0" }, - { name = "psycopg", extras = ["binary"], marker = "extra == 'postgresql'", specifier = ">=3.0" }, + { name = "psycopg", extras = ["binary"], marker = "extra == 'all'", specifier = ">=3.1.17" }, + { name = "psycopg", extras = ["binary"], marker = "extra == 'postgresql'", specifier = ">=3.1.17" }, { name = "pyarrow", specifier = ">=22.0.0" }, { name = "pydantic", specifier = ">=2.0" }, { name = "pyspiral", marker = "extra == 'all'", specifier = ">=0.16.33" }, @@ -2173,7 +2173,7 @@ dev = [ { name = "pip-licenses", specifier = ">=5.0.0" }, { name = "pre-commit", specifier = ">=4.4.0" }, { name = "pre-commit-hooks", specifier = ">=6.0.0" }, - { name = "psycopg", extras = ["binary"], specifier = ">=3.0" }, + { name = "psycopg", extras = ["binary"], specifier = ">=3.1.17" }, { name = "pyarrow-stubs", specifier = ">=20.0.0.20250716" }, { name = "pyiceberg", specifier = ">=0.9.1" }, { name = "pyright", specifier = ">=1.1.404" }, From 09c12b341cb96293879ae88c76ef1950cdc3f4ae Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 21:34:21 -0800 Subject: [PATCH 6/7] fix(sources): one IP address in two spellings keeps the PostgreSQL default id; refuse an address holding '::' (ITL-1267) A host and a hostaddr that are both IP literals are compared by parsed value (0:0:0:0:0:0:0:1 and ::1 are one address; an IPv6 zone counts), so they keep a default id; a name beside an address and two different addresses are still refused. A host that would put '::' into the address (a socket directory holding it or ending with ':') has no default and asks for a source_id, in the wording of the other refusals, instead of failing in location_source_id. The live tests write an IPv6 test server's host as the id and a URI do. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1267.md | 4 +- docs/reference/hashing.md | 6 +- .../core/sources/postgresql_table_source.py | 33 +++++++- .../sources/test_postgresql_table_source.py | 84 +++++++++++++++++++ ...est_postgresql_table_source_integration.py | 24 +++++- 5 files changed, 140 insertions(+), 11 deletions(-) diff --git a/changelog.d/ITL-1267.md b/changelog.d/ITL-1267.md index 05b171573..bf8695834 100644 --- a/changelog.d/ITL-1267.md +++ b/changelog.d/ITL-1267.md @@ -15,7 +15,9 @@ `source_id`: the server reached can change from one connection to the next. So does one whose parameters give a host beside a different `hostaddr` (`host=db.example.org hostaddr=192.0.2.1`), each from the DSN, a service file or the environment, as libpq takes - them: the connection is sent to the address, so the host name does not name the server. A `hostaddr` given alone names the server by that + them: the connection is sent to the address, so the host name does not name the server + (two spellings of one IP address, compared by value, are one address). A host that would put + `::` in the address (a socket directory holding it or ending with `:`) gives no default either. A `hostaddr` given alone names the server by that address. A database, schema or table name holding `/` has no default either, as one holding `.` already had. - `orcapod[postgresql]` requires psycopg 3.1.17 or later (was 3.0). The default PostgreSQL diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 955b3ff98..4a08c0818 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -186,7 +186,8 @@ when they read the same data. The generic `DBTableSource` knows no database, so default and refuses to be built without a `source_id`. A location whose parts cannot be told apart has no default (`joined_location`): a SQLite table name holding `:`, a PostgreSQL or SpiralDB name holding `.`, a PostgreSQL name holding `/`, a SpiralDB address or table id -holding `@`. Such a source needs a `source_id`. +holding `@`, a PostgreSQL address holding `::` (a socket directory holding it or ending with +`:`; `::` separates the parts of a source-info token). Such a source needs a `source_id`. A PostgreSQL default names the server the connection reached (developer, November 18, 2026, ITL-1267), as libpq reports it, so one database, schema and table name on two servers gives @@ -202,7 +203,8 @@ ids (`localhost` and `127.0.0.1`), as two spellings of one CSV path are. A DSN, or `PGHOSTADDR` setting or a service file that names several servers (`host=a,b`) gives no default: the server reached can change from one connection to the next. Neither do parameters that give a host beside a different `hostaddr` (`host=db.example.org -hostaddr=192.0.2.1`; `host=127.0.0.1 hostaddr=127.0.0.1` keeps a default), wherever each +hostaddr=192.0.2.1`; `host=127.0.0.1 hostaddr=127.0.0.1` keeps a default, as do two spellings of +one IP address, compared by value, an IPv6 zone included: `host=0:0:0:0:0:0:0:1 hostaddr=::1`), wherever each comes from. libpq takes each parameter from the DSN, else a service file, else the environment; psycopg (3.1.17 or later, the version `orcapod[postgresql]` requires for this) resolves a single host name of the DSN or `PGHOST` itself, when neither diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index 97c0c4ce0..c69186b7b 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -57,6 +57,21 @@ def _server_name(host: str) -> str: return host.lower() +def _one_address(host: str, hostaddr: str) -> bool: + """Return whether a ``host`` and a ``hostaddr`` name one address. + + Equal text, or two IP literals of one parsed value (``0:0:0:0:0:0:0:1`` and + ``::1``; an IPv6 zone such as ``%eth0`` is part of the value). A host name beside + an address is never one address: what the name resolves to is not seen. + """ + if host == hostaddr: + return True + try: + return ipaddress.ip_address(host) == ipaddress.ip_address(hostaddr) + except ValueError: + return False + + def postgresql_table_address( host: str, port: int, database: str, schema: str, table: str ) -> str: @@ -80,8 +95,10 @@ def postgresql_table_address( The table's address. Raises: - ValueError: If the host is empty, or the database, schema or table name is - empty or holds ``.`` or ``/``; give the source a ``source_id``. + ValueError: If the host is empty, the database, schema or table name is + empty or holds ``.`` or ``/``, or the address would contain ``::`` (a + socket directory holding it, or a host ending with ``:``); give the + source a ``source_id``. """ if not host: raise ValueError( @@ -90,7 +107,15 @@ def postgresql_table_address( ) joined_location("/", database, schema, table) name = joined_location(".", database, schema, table) - return f"{_server_name(host)}:{port}/{name}" + address = f"{_server_name(host)}:{port}/{name}" + if "::" in address: + raise ValueError( + f"the address {address!r} of the PostgreSQL table contains '::' (in the " + "host, such as a socket directory, or in a name), which separates the " + "parts of a source-info token, so the table has no default source id; " + "give the source a source_id" + ) + return address class PostgreSQLTableSource(DBTableSource): @@ -211,7 +236,7 @@ def _table_address(self, connector: DBConnectorProtocol, table_name: str) -> str "connection to the next, so the table has no default source id; give " "the source a source_id" ) - if host and hostaddr and host != hostaddr: + if host and hostaddr and not _one_address(host, hostaddr): raise ValueError( f"the connection parameters of the PostgreSQL source over table " f"{table_name!r} (its DSN, PGHOST or PGHOSTADDR, or a service file) " diff --git a/tests/test_core/sources/test_postgresql_table_source.py b/tests/test_core/sources/test_postgresql_table_source.py index 06d46410e..c9c4c1292 100644 --- a/tests/test_core/sources/test_postgresql_table_source.py +++ b/tests/test_core/sources/test_postgresql_table_source.py @@ -653,6 +653,39 @@ def test_separator_in_a_name_has_no_address( with pytest.raises(ValueError, match="source_id"): postgresql_table_address("localhost", 5432, database, schema, table) + @pytest.mark.parametrize( + "host", + ["/tmp/pg::sock", "/a::b/c", "@pg::sock", "/tmp/pg:", "/tmp/a:b:"], + ids=[ + "socket directory holding ::", + ":: in the middle", + "abstract socket holding ::", + "socket directory ending with ':'", + "':' inside and at the end", + ], + ) + def test_a_host_that_would_put_double_colon_in_the_address_has_none( + self, host: str + ) -> None: + """``::`` separates a source-info token: refused, asking for a source_id.""" + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + with pytest.raises( + ValueError, match="contains '::'.*give the source a source_id" + ): + postgresql_table_address(host, 5432, "orcapod", "public", "t") + + def test_a_single_colon_in_a_socket_directory_is_kept(self) -> None: + from orcapod.core.sources.postgresql_table_source import ( + postgresql_table_address, + ) + + assert postgresql_table_address("/tmp/a:b", 5432, "d", "s", "t") == ( + "/tmp/a:b:5432/d.s.t" + ) + def test_empty_host_has_no_address(self) -> None: from orcapod.core.sources.postgresql_table_source import ( postgresql_table_address, @@ -755,6 +788,57 @@ def test_host_beside_hostaddr_has_no_default(self, given: tuple[str, str]) -> No self._source(connector) connector.current_location.assert_not_called() + @pytest.mark.parametrize( + ("host", "hostaddr"), + [ + ("0:0:0:0:0:0:0:1", "::1"), + ("::1", "0:0:0:0:0:0:0:1"), + ("2001:DB8::1", "2001:db8:0:0:0:0:0:1"), + ("2001:db8:0:0:0:0:0:1", "2001:DB8::1"), + ("fe80::1%eth0", "fe80:0:0:0:0:0:0:1%eth0"), + ], + ids=[ + "exploded host, short address", + "short host, exploded address", + "upper case host", + "upper case address", + "one zone", + ], + ) + def test_two_spellings_of_one_ip_address_name_it( + self, host: str, hostaddr: str + ) -> None: + connector = _server_connector(host, 5432, given=(host, hostaddr)) + source_id = self._source(connector).source_id + assert source_id.startswith("postgresql_table:[") + assert source_id.endswith("]:5432/orcapod.public.measurements") + + @pytest.mark.parametrize( + ("host", "hostaddr"), + [ + ("fe80::1%eth0", "fe80::1"), + ("fe80::1", "fe80::1%eth0"), + ("fe80::1%eth0", "fe80::1%eth1"), + ("::ffff:127.0.0.1", "127.0.0.1"), + ("::1", "::2"), + ("localhost", "::1"), + ], + ids=[ + "zone only on the host", + "zone only on the address", + "two zones", + "IPv4-mapped against IPv4", + "two IPv6 addresses", + "a name beside an IPv6 address", + ], + ) + def test_different_addresses_or_a_name_still_have_no_default( + self, host: str, hostaddr: str + ) -> None: + connector = _server_connector(host, 5432, given=(host, hostaddr)) + with pytest.raises(ValueError, match="host name alone does not identify"): + self._source(connector) + def test_hostaddr_alone_or_equal_to_the_host_names_the_address(self) -> None: # libpq reports the address as the host when no host is given; a host that # is the address itself names it too. diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index d21277061..16c32b5d0 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -16,6 +16,7 @@ from __future__ import annotations +import ipaddress import os import uuid from collections.abc import Iterator, Mapping @@ -325,6 +326,21 @@ def _expected(host: str, schema: str, port: str | None = None) -> str: ) +def _id_host(host: str) -> str: + """How the default id writes the test server's host: an IPv6 address bracketed + and exploded, an IPv4 address as given, a name in lower case.""" + try: + ip = ipaddress.ip_address(host) + except ValueError: + return host.lower() + return f"[{ip.exploded}]" if ip.version == 6 else host + + +def _uri_host(host: str) -> str: + """The test server's host in a URI: an IPv6 address in brackets.""" + return f"[{host}]" if ":" in host else host + + def _requires_localhost() -> None: if _SERVER["host"] != "localhost": pytest.skip("needs the test server at PGHOST=localhost, as in CI") @@ -340,12 +356,12 @@ class TestDefaultSourceIdOnTheServer: def test_uri_and_keyword_dsn_give_one_id(self, server_table: str) -> None: uri = ( - f"postgresql://{_SERVER['user']}:{_SERVER['password']}@{_SERVER['host']}:" + f"postgresql://{_SERVER['user']}:{_SERVER['password']}@{_uri_host(_SERVER['host'])}:" f"{_SERVER['port']}/{_SERVER['dbname']}" f"?options=-csearch_path%3D{server_table}" ) ids = [_source_id(uri), _source_id(_keyword_dsn(server_table))] - assert ids == [_expected(_SERVER["host"].lower(), server_table)] * 2 + assert ids == [_expected(_id_host(_SERVER["host"]), server_table)] * 2 def test_id_never_holds_user_or_password(self, server_table: str) -> None: # Both DSNs carry the user and the password; the id is exactly the host, the @@ -353,12 +369,12 @@ def test_id_never_holds_user_or_password(self, server_table: str) -> None: # check would fail a correct id whenever the user's name is also the # database's, as with PGUSER=postgres PGDATABASE=postgres.) uri = ( - f"postgresql://{_SERVER['user']}:{_SERVER['password']}@{_SERVER['host']}:" + f"postgresql://{_SERVER['user']}:{_SERVER['password']}@{_uri_host(_SERVER['host'])}:" f"{_SERVER['port']}/{_SERVER['dbname']}" f"?options=-csearch_path%3D{server_table}" ) for dsn in (uri, _keyword_dsn(server_table)): - assert _source_id(dsn) == _expected(_SERVER["host"].lower(), server_table) + assert _source_id(dsn) == _expected(_id_host(_SERVER["host"]), server_table) def test_upper_case_host_name_gives_the_lower_case_id( self, server_table: str From 3c589936542bcd8ee8f2cbee38bac7659daef3a7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 22:00:42 -0800 Subject: [PATCH 7/7] fix(sources): keep a drive-qualified PostgreSQL socket directory as given; document this-machine hosts (ITL-1267) A Windows socket directory (C:/PgSockets, c:\pg) is written in the default id as given, like a / or @ path; a host name, one or two letters included, is still lower-cased. The hashing reference says that a socket directory, localhost or a loopback address names this machine, so two machines reading their own servers share a default id and need distinct source_id values when combined. The live tests clear PGSERVICE and build every URI with one helper that percent-encodes its components and brackets an IPv6 literal. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1267.md | 2 +- docs/reference/hashing.md | 8 +++- .../core/sources/postgresql_table_source.py | 11 ++++- .../sources/test_postgresql_table_source.py | 7 +++ ...est_postgresql_table_source_integration.py | 48 +++++++++++-------- 5 files changed, 50 insertions(+), 26 deletions(-) diff --git a/changelog.d/ITL-1267.md b/changelog.d/ITL-1267.md index bf8695834..6c041dfac 100644 --- a/changelog.d/ITL-1267.md +++ b/changelog.d/ITL-1267.md @@ -5,7 +5,7 @@ `postgresql_table:..
`), so one database, schema and table name on two servers gives two ids. The host is the name or address as libpq reports it, a host name in lower case, an IPv6 address in brackets in its exploded form (no `::`), a Unix-domain - socket directory as given; the port is always the number used (without one in the DSN, a + socket directory as given (a Windows one with its drive too); the port is always the number used (without one in the DSN, a service file's, else `PGPORT`, else libpq's compiled default, normally `5432`). No user name, password or other connection parameter enters the id. The system-tag values and source-info tokens of rows read from PostgreSQL without a `source_id` change with it; a diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 4a08c0818..c2dd6917b 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -196,7 +196,7 @@ never the address a name resolved to. A `hostaddr` given alone is the host. A host name is written in lower case (`DB.Example.ORG` and `db.example.org` are one id); an IPv6 address in brackets and in its exploded form, which holds no `::` (`[0000:0000:0000:0000:0000:0000:0000:0001]` for `::1`); an IPv4 address and a socket -directory as given. The port is always the number used: a DSN without one uses the port of +directory as given (a Windows one with its drive, `C:/PgSockets`, keeps its case too). The port is always the number used: a DSN without one uses the port of a service file, else `PGPORT`, else libpq's compiled default (normally `5432`), so a DSN that gives the port the connection would use anyway and one without it give one id. Two spellings of one server are two ids (`localhost` and `127.0.0.1`), as two spellings of one CSV path are. A DSN, a `PGHOST` @@ -218,7 +218,11 @@ sends the connection to the address, so the host name does not name the server, and two such DSNs with one host and two addresses would share an id. A name that DNS, a hosts file or a tunnel sends to another server is not seen in the parameters: two servers reached under one name that way share a default id and -need a `source_id`. No user name, password or other connection parameter enters the id. +need a `source_id`. The same holds for a name that means this machine: a socket directory +(`/var/run/postgresql`), `localhost` or a loopback address (`127.0.0.1`, `::1`). Two +machines that each read their own server that way get one default id for one table name +(`postgresql_table:/var/run/postgresql:5432/d.public.t` on both), so when their rows or +provenance are combined, give each source a distinct `source_id`. No user name, password or other connection parameter enters the id. A row's record id is its row identifier (site 5), chosen by `record_id_columns` (a column name or several, in key order; every source accepts it): diff --git a/src/orcapod/core/sources/postgresql_table_source.py b/src/orcapod/core/sources/postgresql_table_source.py index c69186b7b..0f12aa372 100644 --- a/src/orcapod/core/sources/postgresql_table_source.py +++ b/src/orcapod/core/sources/postgresql_table_source.py @@ -13,6 +13,7 @@ from __future__ import annotations import ipaddress +import re from collections.abc import Collection, Iterator from contextlib import contextmanager from typing import TYPE_CHECKING, Any, ClassVar, cast @@ -31,13 +32,19 @@ from orcapod.config import OrcapodConfig +# A drive-qualified Windows socket directory (``C:/PgSockets``, ``c:\\pg``): libpq takes +# it as a path, not a host name, so it keeps its case. +_WINDOWS_DIRECTORY = re.compile(r"[A-Za-z]:[\\/]") + + def _server_name(host: str) -> str: """Return the host as it is written in a default source id. A host name is lower-cased (DNS names are case-insensitive); an IPv6 address is bracketed, as in a URI, in its exploded form, so it never holds ``::`` and has one spelling (a zone, ``%eth0``, is kept as given); an IPv4 address and a socket path - (``/...``, or ``@...`` for a Linux abstract socket) are kept as given. + (``/...``, ``@...`` for a Linux abstract socket, or a drive-qualified Windows + directory such as ``C:/PgSockets`` or ``c:\\pg``) are kept as given. Args: host: The host the connection reports (``PQhost``). @@ -52,7 +59,7 @@ def _server_name(host: str) -> str: ip = None if isinstance(ip, ipaddress.IPv6Address): return f"[{ip.exploded}{zone_mark}{zone}]" - if ip is not None or host.startswith(("/", "@")): + if ip is not None or host.startswith(("/", "@")) or _WINDOWS_DIRECTORY.match(host): return host return host.lower() diff --git a/tests/test_core/sources/test_postgresql_table_source.py b/tests/test_core/sources/test_postgresql_table_source.py index c9c4c1292..b00d88da7 100644 --- a/tests/test_core/sources/test_postgresql_table_source.py +++ b/tests/test_core/sources/test_postgresql_table_source.py @@ -610,6 +610,13 @@ class TestTableAddress: ("/Tmp/PG", 5433, "/Tmp/PG:5433/orcapod.public.t"), # A Linux abstract-namespace socket, as reported. ("@pgsock", 5432, "@pgsock:5432/orcapod.public.t"), + # A drive-qualified Windows socket directory, as reported, case kept. + ("C:/PgSockets", 5432, "C:/PgSockets:5432/orcapod.public.t"), + ("c:\\Pg", 5433, "c:\\Pg:5433/orcapod.public.t"), + ("D:/X/Y", 5432, "D:/X/Y:5432/orcapod.public.t"), + # A one-letter or two-letter DNS name is still a name: lower-cased. + ("C", 5432, "c:5432/orcapod.public.t"), + ("Db", 5433, "db:5433/orcapod.public.t"), ], ) def test_address(self, host: str, port: int, expected: str) -> None: diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index 16c32b5d0..46592b213 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -19,8 +19,9 @@ import ipaddress import os import uuid -from collections.abc import Iterator, Mapping +from collections.abc import Iterator, Mapping, Sequence from types import MappingProxyType +from urllib.parse import quote, urlencode import pytest @@ -308,8 +309,8 @@ def server_table(pg_schema: str) -> str: @pytest.fixture def no_server_env(monkeypatch: pytest.MonkeyPatch) -> None: - """Keep the PG* host and port variables out of the DSNs a test builds.""" - for envvar in ("PGHOST", "PGHOSTADDR", "PGPORT"): + """Keep the PG* host, port and service variables out of the DSNs a test builds.""" + for envvar in ("PGHOST", "PGHOSTADDR", "PGPORT", "PGSERVICE"): monkeypatch.delenv(envvar, raising=False) @@ -336,9 +337,25 @@ def _id_host(host: str) -> str: return f"[{ip.exploded}]" if ip.version == 6 else host -def _uri_host(host: str) -> str: - """The test server's host in a URI: an IPv6 address in brackets.""" - return f"[{host}]" if ":" in host else host +def _uri( + schema: str, *, host: str | None = None, query: Sequence[tuple[str, str]] = () +) -> str: + """A URI DSN for the test server, every component percent-encoded. + + ``host`` defaults to the test server's; ``""`` leaves it out (the query then + names the server). An IPv6 literal is bracketed, its zone's ``%`` encoded. + """ + server = _SERVER["host"] if host is None else host + if ":" in server: + netloc_host = "[" + server.replace("%", "%25") + "]" + else: + netloc_host = quote(server, safe="") + params = [*query, ("options", f"-csearch_path={schema}")] + return ( + f"postgresql://{quote(_SERVER['user'], safe='')}:" + f"{quote(_SERVER['password'], safe='')}@{netloc_host}:{_SERVER['port']}/" + f"{quote(_SERVER['dbname'], safe='')}?{urlencode(params, quote_via=quote)}" + ) def _requires_localhost() -> None: @@ -355,11 +372,7 @@ class TestDefaultSourceIdOnTheServer: """ def test_uri_and_keyword_dsn_give_one_id(self, server_table: str) -> None: - uri = ( - f"postgresql://{_SERVER['user']}:{_SERVER['password']}@{_uri_host(_SERVER['host'])}:" - f"{_SERVER['port']}/{_SERVER['dbname']}" - f"?options=-csearch_path%3D{server_table}" - ) + uri = _uri(server_table) ids = [_source_id(uri), _source_id(_keyword_dsn(server_table))] assert ids == [_expected(_id_host(_SERVER["host"]), server_table)] * 2 @@ -368,11 +381,7 @@ def test_id_never_holds_user_or_password(self, server_table: str) -> None: # port and the three-part name, with room for nothing else. (A substring # check would fail a correct id whenever the user's name is also the # database's, as with PGUSER=postgres PGDATABASE=postgres.) - uri = ( - f"postgresql://{_SERVER['user']}:{_SERVER['password']}@{_uri_host(_SERVER['host'])}:" - f"{_SERVER['port']}/{_SERVER['dbname']}" - f"?options=-csearch_path%3D{server_table}" - ) + uri = _uri(server_table) for dsn in (uri, _keyword_dsn(server_table)): assert _source_id(dsn) == _expected(_id_host(_SERVER["host"]), server_table) @@ -441,11 +450,8 @@ def test_host_beside_hostaddr_in_the_dsn_has_no_default( if form == "keyword": dsn = _keyword_dsn(server_table, **{key: server[key] for key in order}) else: - query = "&".join(f"{key}={server[key]}" for key in order) - dsn = ( - f"postgresql://{_SERVER['user']}:{_SERVER['password']}@:" - f"{_SERVER['port']}/{_SERVER['dbname']}?{query}" - f"&options=-csearch_path%3D{server_table}" + dsn = _uri( + server_table, host="", query=[(key, server[key]) for key in order] ) with pytest.raises(ValueError, match="host name alone does not identify"): _source_id(dsn)