From ae051e668fb8494b6d1c9e0e113fa2ee856fb17b Mon Sep 17 00:00:00 2001 From: Clay McGinnis Date: Thu, 19 Nov 2026 20:16:15 -0800 Subject: [PATCH 1/4] feat(dbapi): carry signed execution ownership claims --- tests/test_driver.py | 21 +++++ tests/test_reconnect.py | 119 +++++++++++++++++++++++++++++ wherobots/db/__init__.py | 5 +- wherobots/db/connection.py | 153 ++++++++++++++++++++++++++++++++----- wherobots/db/constants.py | 1 + wherobots/db/cursor.py | 53 ++++++++++--- wherobots/db/driver.py | 31 +++++++- wherobots/db/errors.py | 8 ++ wherobots/db/models.py | 45 ++++++++++- 9 files changed, 401 insertions(+), 35 deletions(-) diff --git a/tests/test_driver.py b/tests/test_driver.py index b01cd03..363bd2f 100644 --- a/tests/test_driver.py +++ b/tests/test_driver.py @@ -1,5 +1,6 @@ """Tests for the connect() and connect_direct() driver functions.""" +import logging import threading import time from importlib import metadata @@ -545,6 +546,26 @@ def test_cancel_before_ws_connect(self, mock_ws): class TestConnectDirectWebSocket: + @patch("wherobots.db.driver.websockets.sync.client.connect") + def test_required_ownership_rejects_older_server_before_submission(self, mock_ws): + ws = mock_ws.return_value + ws.subprotocol = None + + with pytest.raises( + InterfaceError, match="does not support execution ownership" + ): + connect_direct( + uri="wss://compute.example.com/sql/org/session-id", + require_execution_ownership=True, + ) + + assert mock_ws.call_args.kwargs["subprotocols"] == [ + "wherobots.execution-ownership.v1" + ] + assert not mock_ws.call_args.kwargs["logger"].isEnabledFor(logging.DEBUG) + ws.close.assert_called_once() + ws.send.assert_not_called() + @patch("wherobots.db.driver.websockets.sync.client.connect") def test_close_handshake_is_bounded(self, mock_ws): from websockets.exceptions import ConnectionClosedOK diff --git a/tests/test_reconnect.py b/tests/test_reconnect.py index daceadb..791a970 100644 --- a/tests/test_reconnect.py +++ b/tests/test_reconnect.py @@ -7,6 +7,7 @@ import threading import time from unittest.mock import MagicMock, patch +from hashlib import sha256 import cbor2 import pandas @@ -21,8 +22,12 @@ ConnectionLostError, ExecutionCancelledError, ExecutionNotFoundError, + ExecutionOwnership, + ExecutionOwnershipError, + ProgrammingError, ) from wherobots.db.connection import Connection +from wherobots.db.constants import OWNERSHIP_SUBPROTOCOL from wherobots.db.driver import connect_direct from wherobots.db.errors import InterfaceError from wherobots.db.models import Store, StoreResult @@ -478,6 +483,120 @@ def test_a_cancel_sent_before_the_loss_is_sent_again_after_the_attach(): conn.close() +def test_protected_reconnect_preserves_claim_without_replaying_sql(caplog): + lost = Session() + again = new_session("running", ownership_generation=1) + lost.subprotocol = again.subprotocol = OWNERSHIP_SUBPROTOCOL + public_key = "01" * 32 + execution_id = "owned_" + sha256(bytes.fromhex(public_key)).hexdigest() + ownership = ExecutionOwnership(execution_id, 1, "ab" * 64, public_key) + conn = open_connection(lost, Factory(again), require_execution_ownership=True) + try: + with caplog.at_level(logging.DEBUG): + cursor = conn.cursor() + cursor.execute("SELECT 1", ownership=ownership) + assert lost.sent[0]["ownership"] == { + **ownership.claim(), + "public_key": public_key, + } + cursor.close() + assert lost.sent[-1]["ownership"] == ownership.claim() + lost.drop() + assert wait_until(lambda: len(again.sent) >= 2) + assert again.kinds()[:2] == ["retrieve_results", "cancel"] + assert again.sent[0]["attach"] is True + assert again.sent[0]["ownership"] == { + **ownership.claim(), + "public_key": public_key, + } + assert again.sent[1]["ownership"] == ownership.claim() + assert not again.requests("execute_sql") + assert ownership.signature not in caplog.text + finally: + conn.close() + + +@pytest.mark.parametrize("server_generation", [None, 2]) +def test_protected_terminal_event_requires_authenticated_result(server_generation): + session = Session() + session.subprotocol = OWNERSHIP_SUBPROTOCOL + public_key = "01" * 32 + execution_id = "owned_" + sha256(bytes.fromhex(public_key)).hexdigest() + ownership = ExecutionOwnership(execution_id, 1, "ab" * 64, public_key) + conn = open_connection(session, Factory(), require_execution_ownership=True) + try: + cursor = conn.cursor() + cursor.execute("SELECT 1", store=STORE, ownership=ownership) + session.put( + kind="state_updated", + execution_id=execution_id, + state="succeeded", + result_uri=RESULT_URI, + ) + assert wait_until(lambda: session.requests("retrieve_results", execution_id)) + assert ( + session.requests("retrieve_results", execution_id)[0]["ownership"] + == ownership.claim() + ) + if server_generation is None: + session.put( + kind="error", + execution_id=execution_id, + message="Execution ownership generation is stale", + ) + else: + session.put( + kind="execution_result", + execution_id=execution_id, + state="succeeded", + result_uri=RESULT_URI, + ownership_generation=server_generation, + ) + assert isinstance(outcome(cursor).error, ExecutionOwnershipError) + assert outcome(cursor).error.execution_id == execution_id + finally: + conn.close() + + +def test_used_protected_id_carries_unknown_outcome(): + session = Session() + session.subprotocol = OWNERSHIP_SUBPROTOCOL + public_key = "01" * 32 + execution_id = "owned_" + sha256(bytes.fromhex(public_key)).hexdigest() + ownership = ExecutionOwnership(execution_id, 1, "ab" * 64, public_key) + conn = open_connection(session, Factory(), require_execution_ownership=True) + try: + cursor = conn.cursor() + cursor.execute("SELECT 1", ownership=ownership) + session.put( + kind="error", + execution_id=execution_id, + message="Protected execution ID already used", + ) + error = outcome(cursor).error + assert isinstance(error, ExecutionOwnershipError) + assert error.execution_id == execution_id + assert "original may have run" in str(error) + assert len(session.requests("execute_sql", execution_id)) == 1 + finally: + conn.close() + + +@pytest.mark.parametrize( + ("generation", "signature", "public_key", "message"), + [ + (True, "ab" * 64, "01" * 32, "generation"), + (1, "too short", "01" * 32, "signature"), + (1, "ab" * 64, "zz" * 32, "public key"), + ], +) +def test_malformed_ownership_is_rejected_before_sending( + generation, signature, public_key, message +): + with pytest.raises(ProgrammingError, match=message): + ExecutionOwnership("unused", generation, signature, public_key) + + # Giving up diff --git a/wherobots/db/__init__.py b/wherobots/db/__init__.py index 7324d31..9ee5c0a 100644 --- a/wherobots/db/__init__.py +++ b/wherobots/db/__init__.py @@ -7,13 +7,14 @@ DatabaseError, ExecutionCancelledError, ExecutionNotFoundError, + ExecutionOwnershipError, InternalError, InterfaceError, OperationalError, ProgrammingError, NotSupportedError, ) -from .models import ProgressInfo, Store, StoreResult +from .models import ExecutionOwnership, ProgressInfo, Store, StoreResult from .region import Region from .runtime import Runtime from .types import StorageFormat @@ -32,6 +33,8 @@ "ConnectionLostError", "ExecutionCancelledError", "ExecutionNotFoundError", + "ExecutionOwnership", + "ExecutionOwnershipError", "ProgrammingError", "NotSupportedError", "Region", diff --git a/wherobots/db/connection.py b/wherobots/db/connection.py index ae78bc4..1be869a 100644 --- a/wherobots/db/connection.py +++ b/wherobots/db/connection.py @@ -21,6 +21,7 @@ DEFAULT_READ_TIMEOUT_SECONDS, DEFAULT_RECONNECT_TIMEOUT_SECONDS, DEFAULT_STALE_QUERY_PROBE_SECONDS, + OWNERSHIP_SUBPROTOCOL, ) from ._transport import abort_connection, socket_writable from .cursor import Cursor @@ -28,12 +29,19 @@ ConnectionLostError, ExecutionCancelledError, ExecutionNotFoundError, + ExecutionOwnershipError, InterfaceError, NotSupportedError, OperationalError, ProgrammingError, ) -from .models import ExecutionResult, ProgressInfo, Store, StoreResult +from .models import ( + ExecutionOwnership, + ExecutionResult, + ProgressInfo, + Store, + StoreResult, +) from .types import ( RequestKind, EventKind, @@ -237,6 +245,7 @@ class Query: state: ExecutionState handler: Callable[[Any], None] store: Store | None = None + ownership: ExecutionOwnership | None = None watch: _Watch = field(default_factory=_Watch) attach: _Attach | None = None """Set once the query is re-attached after reconnecting.""" @@ -290,6 +299,7 @@ def __init__( session_key: str | None = None, session_stopper: Callable[[], None] | None = None, session_key_exclusive: bool = False, + require_execution_ownership: bool = False, ): """ :param transport_factory: Opens a new WebSocket to the same SQL session, given @@ -308,6 +318,10 @@ def __init__( :param session_key_exclusive: See :attr:`session_key_exclusive`. """ self.__ws = ws + if require_execution_ownership and ws.subprotocol != OWNERSHIP_SUBPROTOCOL: + ws.close() + raise InterfaceError("SQL session does not support execution ownership") + self.__require_execution_ownership = require_execution_ownership self.__transport_factory = transport_factory self.__reconnect_within = ( _positive_seconds(reconnect_timeout_seconds) @@ -742,7 +756,7 @@ def __resume(self, ws: websockets.sync.client.ClientConnection) -> bool: query.state = ExecutionState.RESULTS_REQUESTED query.watch = _Watch() query.attach = _Attach() - cancelled = [q.execution_id for q in pending if q.cancel_requested] + cancelled = [query for query in pending if query.cancel_requested] if closed: try: abort_connection(ws) @@ -756,12 +770,9 @@ def __resume(self, ws: websockets.sync.client.ClientConnection) -> bool: len(pending), ) requests = [ - self.__retrieve_request(query.execution_id, attach=True) + self.__retrieve_request(query.execution_id, query.ownership, attach=True) for query in pending - ] + [ - {"kind": RequestKind.CANCEL.value, "execution_id": execution_id} - for execution_id in cancelled - ] + ] + [self.__cancel_request(query) for query in cancelled] try: for request in requests: ws.send(json.dumps(request)) @@ -973,6 +984,17 @@ def fail_attached(error: OperationalError) -> None: # Incoming state transitions are handled here. if kind == EventKind.STATE_UPDATED or kind == EventKind.EXECUTION_RESULT: + if ( + kind == EventKind.EXECUTION_RESULT + and query.ownership is not None + and message.get("ownership_generation") != query.ownership.generation + ): + fail_attached( + ExecutionOwnershipError( + "SQL session did not confirm execution ownership", execution_id + ) + ) + return try: query.state = ExecutionState[message["state"].upper()] logging.info("Query %s is now %s.", execution_id, query.state) @@ -980,6 +1002,23 @@ def fail_attached(error: OperationalError) -> None: fail_query("interpret", error) return + if ( + kind == EventKind.STATE_UPDATED + and query.ownership is not None + and query.state + in ( + ExecutionState.SUCCEEDED, + ExecutionState.FAILED, + ExecutionState.CANCELLED, + ) + ): + if not query.watch.results_requested: + try: + self.__request_results(execution_id) + except Exception as error: + fail_query("request", error) + return + if attach_reply and attach is not None: if attach.acknowledged: logging.info("Attached to execution %s.", execution_id) @@ -1045,9 +1084,11 @@ def fail_attached(error: OperationalError) -> None: if ( query.store is not None and (results is None or results == {}) - and attach is not None + and (attach is not None or query.ownership is not None) ): - if attach.acknowledged: + if query.ownership is not None or ( + attach is not None and attach.acknowledged + ): # A session that supports attaching also echoes the # result location, so this is an empty store result. logging.info( @@ -1112,7 +1153,7 @@ def fail_attached(error: OperationalError) -> None: query.state = ExecutionState.COMPLETED complete_query(ExecutionResult(results=decoded)) elif query.state == ExecutionState.CANCELLED: - if attach is not None: + if attach is not None or query.ownership is not None: with self.__lock: requested = query.cancel_requested if not requested: @@ -1139,12 +1180,44 @@ def fail_attached(error: OperationalError) -> None: ) complete_query(ExecutionResult(results=pandas.DataFrame())) elif query.state == ExecutionState.FAILED: + if query.ownership is not None and kind == EventKind.EXECUTION_RESULT: + failure = ( + message.get("exception_on_failure") or "SQL execution failed" + ) + fail_attached(OperationalError(failure)) # Don't do anything here; the ERROR event is coming with more # details. pass elif kind == EventKind.ERROR: error = message.get("message") not_found = error == _EXECUTION_NOT_FOUND + if query.ownership is not None: + if error == "Protected execution ID already used": + fail_attached( + ExecutionOwnershipError( + "Protected execution ID already used. The original may have run. " + "Verify its outcome before retrying.", + execution_id, + ) + ) + return + if error in ( + "Execution ownership claim rejected", + "Execution ownership generation is stale", + "Protected execution ID limit reached", + ): + fail_attached(ExecutionOwnershipError(error, execution_id)) + return + if not_found: + fail_attached( + ExecutionNotFoundError( + f"Protected execution {execution_id} is unavailable. " + "It may already have run. Verify its outcome before retrying.", + session_id=self.__session_id, + execution_id=execution_id, + ) + ) + return if attach_reply and not_found: # Unlike for a probe, there's no terminal event to wait for: # the session doesn't know the execution at all. @@ -1317,6 +1390,8 @@ def __redacted_request(message: Dict[str, Any]) -> str: ``statement``; this driver is embedded by other services, so logging it -- even at DEBUG -- would leak raw SQL into their log streams (WBC-139). """ + if "ownership" in message: + message = {**message, "ownership": "[redacted]"} statement = message.get("statement") if isinstance(statement, str): message = {**message, "statement": redact_sql(statement)} @@ -1344,14 +1419,24 @@ def __execute_sql( sql: str, handler: Callable[[Any], None], store: Store | None = None, + *, + ownership: ExecutionOwnership | None = None, ) -> str: """Triggers the execution of the given SQL query.""" - execution_id = str(uuid.uuid4()) - request = { + self.__validate_ownership(ownership) + execution_id = ownership.execution_id if ownership else str(uuid.uuid4()) + request: Dict[str, Any] = { "kind": RequestKind.EXECUTE_SQL.value, "execution_id": execution_id, "statement": sql, } + if ownership is not None: + if ownership.generation != 1: + raise ProgrammingError("Protected submission requires generation 1") + request["ownership"] = { + **ownership.claim(), + "public_key": ownership.public_key, + } if self.__progress_handler is not None: request["enable_progress_events"] = True @@ -1375,6 +1460,7 @@ def __execute_sql( state=ExecutionState.EXECUTION_REQUESTED, handler=handler, store=store, + ownership=ownership, ), ) return execution_id @@ -1384,22 +1470,39 @@ def __attach_query( execution_id: str, handler: Callable[[Any], None], store: Store | None = None, + *, + ownership: ExecutionOwnership | None = None, ) -> str: + self.__validate_ownership(ownership) + if ownership is not None and ownership.execution_id != execution_id: + raise ProgrammingError("Ownership claim is for a different execution") self.__send( - self.__retrieve_request(execution_id, attach=True), + self.__retrieve_request(execution_id, ownership, attach=True), Query( sql="", execution_id=execution_id, state=ExecutionState.RESULTS_REQUESTED, handler=handler, store=store, + ownership=ownership, attach=_Attach(), ), ) return execution_id + def __validate_ownership(self, ownership: ExecutionOwnership | None) -> None: + if ownership is None: + if self.__require_execution_ownership: + raise ProgrammingError("An execution ownership claim is required") + elif not self.__require_execution_ownership: + raise NotSupportedError("Connect with require_execution_ownership=True") + def __retrieve_request( - self, execution_id: str, attach: bool = False + self, + execution_id: str, + ownership: ExecutionOwnership | None, + *, + attach: bool = False, ) -> Dict[str, Any]: request: Dict[str, Any] = { "kind": RequestKind.RETRIEVE_RESULTS.value, @@ -1413,6 +1516,10 @@ def __retrieve_request( request["geometry"] = self.__geometry_representation.value if attach: request["attach"] = True + if ownership is not None: + request["ownership"] = ownership.claim() + if attach: + request["ownership"]["public_key"] = ownership.public_key return request def __request_results( @@ -1428,7 +1535,7 @@ def __request_results( if not query: return True - request = self.__retrieve_request(execution_id, attach=attach) + request = self.__retrieve_request(execution_id, query.ownership, attach=attach) if not probe: # A probe only asks; the reply carries the query's actual state. @@ -1440,12 +1547,18 @@ def __request_results( def __cancel_query(self, execution_id: str) -> None: """Cancels the query with the given execution ID.""" with self.__lock: - if execution_id not in self.__queries: + query = self.__queries.get(execution_id) + if query is None: return + logging.info("Cancelling query %s...", execution_id) + self.__send(self.__cancel_request(query)) - request = { + @staticmethod + def __cancel_request(query: Query) -> Dict[str, Any]: + request: Dict[str, Any] = { "kind": RequestKind.CANCEL.value, - "execution_id": execution_id, + "execution_id": query.execution_id, } - logging.info("Cancelling query %s...", execution_id) - self.__send(request) + if query.ownership is not None: + request["ownership"] = query.ownership.claim() + return request diff --git a/wherobots/db/constants.py b/wherobots/db/constants.py index 961a12a..ca3cafb 100644 --- a/wherobots/db/constants.py +++ b/wherobots/db/constants.py @@ -32,3 +32,4 @@ PROTOCOL_VERSION: Version = Version("1.0.0") PARAM_STYLE = "pyformat" +OWNERSHIP_SUBPROTOCOL = "wherobots.execution-ownership.v1" diff --git a/wherobots/db/cursor.py b/wherobots/db/cursor.py index f62bcaa..9c570c0 100644 --- a/wherobots/db/cursor.py +++ b/wherobots/db/cursor.py @@ -1,10 +1,10 @@ import math import queue import re -from typing import Any, Callable, List, Tuple, Dict +from typing import Any, Callable, List, Tuple, Dict, Protocol from .errors import NotSupportedError, ProgrammingError -from .models import ExecutionResult, Store, StoreResult +from .models import ExecutionOwnership, ExecutionResult, Store, StoreResult # Matches pyformat parameter markers: %(name)s _PYFORMAT_RE = re.compile(r"%\(([^)]+)\)s") @@ -66,13 +66,25 @@ def replacer(match: re.Match) -> str: } +class _AttachCallback(Protocol): + def __call__( + self, + execution_id: str, + handler: Callable[[ExecutionResult], None], + store: Store | None, + /, + *, + ownership: ExecutionOwnership | None = None, + ) -> str: + ... + + class Cursor: def __init__( self, exec_fn, cancel_fn, - attach_fn: Callable[[str, Callable[[ExecutionResult], None], Store | None], str] - | None = None, + attach_fn: _AttachCallback | None = None, ) -> None: self.__exec_fn = exec_fn self.__cancel_fn = cancel_fn @@ -186,22 +198,34 @@ def execute( operation: str, parameters: Dict[str, Any] | None = None, store: Store | None = None, + *, + ownership: ExecutionOwnership | None = None, ) -> None: self.__reset_execution() - self.__current_execution_id = self.__exec_fn( - _substitute_parameters(operation, parameters), - self.__queue.put, - store, - ) + statement = _substitute_parameters(operation, parameters) + if ownership is None: + self.__current_execution_id = self.__exec_fn( + statement, self.__queue.put, store + ) + else: + self.__current_execution_id = self.__exec_fn( + statement, self.__queue.put, store, ownership=ownership + ) - def attach(self, execution_id: str, store: Store | None = None) -> None: + def attach( + self, + execution_id: str, + store: Store | None = None, + *, + ownership: ExecutionOwnership | None = None, + ) -> None: """Retrieve an existing execution on this connection's SQL session. Connect to the original SQL session first. Pass the original Store for stored results. This never submits SQL or extends server result retention; a missing execution raises ExecutionNotFoundError when fetching. On SQL sessions that support attachment, this transfers event ownership. - It does not fence other connections; callers must coordinate the handoff. + For a protected execution, supply the coordinator's ownership claim. """ if not isinstance(execution_id, str) or not execution_id.strip(): raise ProgrammingError("execution_id must be a non-empty string") @@ -211,7 +235,12 @@ def attach(self, execution_id: str, store: Store | None = None) -> None: raise ProgrammingError("This cursor already tracks the execution") # Preserve the current execution until the new attachment is accepted. results: queue.Queue[ExecutionResult] = queue.Queue() - attached_id = self.__attach_fn(execution_id, results.put, store) + if ownership is None: + attached_id = self.__attach_fn(execution_id, results.put, store) + else: + attached_id = self.__attach_fn( + execution_id, results.put, store, ownership=ownership + ) self.__reset_execution() self.__queue = results self.__current_execution_id = attached_id diff --git a/wherobots/db/driver.py b/wherobots/db/driver.py index 9b32bf4..8502467 100644 --- a/wherobots/db/driver.py +++ b/wherobots/db/driver.py @@ -16,6 +16,7 @@ import urllib.parse import websockets.exceptions import websockets.sync.client +from websockets.typing import Subprotocol import certifi from .connection import Connection @@ -28,6 +29,7 @@ DEFAULT_SESSION_WAIT_TIMEOUT_SECONDS, DEFAULT_STALE_QUERY_PROBE_SECONDS, MAX_MESSAGE_SIZE, + OWNERSHIP_SUBPROTOCOL, PARAM_STYLE, PROTOCOL_VERSION, SESSION_FALLBACK_HEADER, @@ -58,6 +60,12 @@ DEFAULT_HTTP_TIMEOUT = 30 +class _OwnershipTransportLogger(logging.LoggerAdapter): + def isEnabledFor(self, level: int) -> bool: + # WebSocket frame tracing includes credentials in the message body. + return level >= logging.INFO and super().isEnabledFor(level) + + def _resolve_dbapi_version() -> str: """Resolve this package's version, or "unknown" if it can't be found.""" try: @@ -132,6 +140,7 @@ def connect( session_key: Union[str, None] = None, reconnect_timeout_seconds: Union[float, None] = DEFAULT_RECONNECT_TIMEOUT_SECONDS, session_key_exclusive: bool = False, + require_execution_ownership: bool = False, ) -> Connection: """Create a connection to a Wherobots SQL session. @@ -175,6 +184,7 @@ def connect( another key, so the connection can stop it without cutting off another client. Requires ``session_key``. The connection's ``session_key_exclusive`` says whether the API did. + :param require_execution_ownership: See :func:`connect_direct`. """ if not token and not api_key: raise ValueError("At least one of `token` or `api_key` is required") @@ -359,6 +369,7 @@ def stop_session() -> None: session_key=session_key_on_api, session_stopper=stop_session, session_key_exclusive=session_key_exclusive_on_api, + require_execution_ownership=require_execution_ownership, ) @@ -393,6 +404,7 @@ def connect_direct( session_key: str | None = None, session_stopper: Union[Callable[[], None], None] = None, session_key_exclusive: bool = False, + require_execution_ownership: bool = False, ) -> Connection: """Connect to a SQL session's WebSocket endpoint directly. @@ -408,6 +420,8 @@ def connect_direct( :meth:`Connection.stop_session`. ``connect()`` supplies it. Without it, the connection can't stop its session. :param session_key_exclusive: See :attr:`Connection.session_key_exclusive`. + :param require_execution_ownership: Require SQL-session ownership support before + sending any SQL. Such connections require a claim on execute and attach. """ uri_with_protocol = f"{uri}/{protocol}" ssl_context = ssl.create_default_context() @@ -418,14 +432,28 @@ def open_ws( ) -> websockets.sync.client.ClientConnection: _check_cancelled(cancel_event) logging.info("Connecting to SQL session at %s ...", uri_with_protocol) - return websockets.sync.client.connect( + ws = websockets.sync.client.connect( uri=uri_with_protocol, additional_headers=headers, max_size=MAX_MESSAGE_SIZE, open_timeout=open_timeout, close_timeout=DEFAULT_CLOSE_TIMEOUT_SECONDS, ssl=ssl_context, + subprotocols=( + [Subprotocol(OWNERSHIP_SUBPROTOCOL)] + if require_execution_ownership + else None + ), + logger=( + _OwnershipTransportLogger(logging.getLogger("websockets.client")) + if require_execution_ownership + else None + ), ) + if require_execution_ownership and ws.subprotocol != OWNERSHIP_SUBPROTOCOL: + ws.close() + raise InterfaceError("SQL session does not support execution ownership") + return ws @tenacity.retry( stop=tenacity.stop_after_attempt(5), @@ -485,4 +513,5 @@ def open_transport(timeout: float) -> websockets.sync.client.ClientConnection: session_key=session_key, session_stopper=session_stopper, session_key_exclusive=session_key_exclusive, + require_execution_ownership=require_execution_ownership, ) diff --git a/wherobots/db/errors.py b/wherobots/db/errors.py index 62eca0e..09bd4d1 100644 --- a/wherobots/db/errors.py +++ b/wherobots/db/errors.py @@ -26,6 +26,14 @@ class NotSupportedError(DatabaseError): pass +class ExecutionOwnershipError(OperationalError): + """SQL-session rejected or could not confirm the execution ownership claim.""" + + def __init__(self, message: str, execution_id: str) -> None: + super().__init__(message) + self.execution_id = execution_id + + class ConnectionLostError(OperationalError): """The connection to the SQL session was lost while a query was pending. diff --git a/wherobots/db/models.py b/wherobots/db/models.py index ed1b75d..5796e8c 100644 --- a/wherobots/db/models.py +++ b/wherobots/db/models.py @@ -1,12 +1,55 @@ -from dataclasses import dataclass +from dataclasses import dataclass, field +from hashlib import sha256 +import re from typing import Any, Dict import pandas from .constants import DEFAULT_STORAGE_FORMAT +from .errors import ProgrammingError from .types import StorageFormat +@dataclass(frozen=True) +class ExecutionOwnership: + """A claim from the coordinator for a preallocated SQL execution ID.""" + + execution_id: str + generation: int + signature: str = field(repr=False) + public_key: str + + def __post_init__(self) -> None: + if ( + isinstance(self.generation, bool) + or not isinstance(self.generation, int) + or not 1 <= self.generation <= 2**63 - 1 + ): + raise ProgrammingError( + "Ownership generation must be a positive 64-bit integer" + ) + if not isinstance(self.signature, str) or not re.fullmatch( + r"[0-9a-fA-F]{128}", self.signature + ): + raise ProgrammingError( + "Ownership signature must contain 128 hex characters" + ) + if not isinstance(self.public_key, str) or not re.fullmatch( + r"[0-9a-fA-F]{64}", self.public_key + ): + raise ProgrammingError( + "Ownership public key must contain 64 hex characters" + ) + expected_id = "owned_" + sha256(bytes.fromhex(self.public_key)).hexdigest() + if self.execution_id != expected_id: + raise ProgrammingError( + "Execution ID does not match the ownership public key" + ) + + def claim(self) -> dict[str, str | int]: + return {"generation": self.generation, "signature": self.signature} + + @dataclass(frozen=True) class StoreResult: """Result information when a query's results are stored to cloud storage. From ab5856f8e60e0e9b58a74ebbf4d913e9ef15d41a Mon Sep 17 00:00:00 2001 From: Clay McGinnis Date: Thu, 19 Nov 2026 20:28:14 -0800 Subject: [PATCH 2/4] fix(dbapi): enforce ownership on replacement transports --- tests/test_reconnect.py | 60 +++++++++++++++++++++++--------------- wherobots/db/connection.py | 23 ++++++++++----- wherobots/db/driver.py | 6 +--- wherobots/db/models.py | 13 ++------- 4 files changed, 56 insertions(+), 46 deletions(-) diff --git a/tests/test_reconnect.py b/tests/test_reconnect.py index 791a970..0fa4c18 100644 --- a/tests/test_reconnect.py +++ b/tests/test_reconnect.py @@ -7,7 +7,6 @@ import threading import time from unittest.mock import MagicMock, patch -from hashlib import sha256 import cbor2 import pandas @@ -487,28 +486,21 @@ def test_protected_reconnect_preserves_claim_without_replaying_sql(caplog): lost = Session() again = new_session("running", ownership_generation=1) lost.subprotocol = again.subprotocol = OWNERSHIP_SUBPROTOCOL - public_key = "01" * 32 - execution_id = "owned_" + sha256(bytes.fromhex(public_key)).hexdigest() - ownership = ExecutionOwnership(execution_id, 1, "ab" * 64, public_key) + execution_id = "owned_" + "12" * 32 + ownership = ExecutionOwnership(execution_id, 1, "ab" * 64) conn = open_connection(lost, Factory(again), require_execution_ownership=True) try: with caplog.at_level(logging.DEBUG): cursor = conn.cursor() cursor.execute("SELECT 1", ownership=ownership) - assert lost.sent[0]["ownership"] == { - **ownership.claim(), - "public_key": public_key, - } + assert lost.sent[0]["ownership"] == ownership.claim() cursor.close() assert lost.sent[-1]["ownership"] == ownership.claim() lost.drop() assert wait_until(lambda: len(again.sent) >= 2) assert again.kinds()[:2] == ["retrieve_results", "cancel"] assert again.sent[0]["attach"] is True - assert again.sent[0]["ownership"] == { - **ownership.claim(), - "public_key": public_key, - } + assert again.sent[0]["ownership"] == ownership.claim() assert again.sent[1]["ownership"] == ownership.claim() assert not again.requests("execute_sql") assert ownership.signature not in caplog.text @@ -516,13 +508,34 @@ def test_protected_reconnect_preserves_claim_without_replaying_sql(caplog): conn.close() +def test_protected_reconnect_rejects_a_replacement_without_ownership_support(): + lost, replacement = Session(), Session() + lost.subprotocol = OWNERSHIP_SUBPROTOCOL + replacement.subprotocol = None + execution_id = "owned_" + "12" * 32 + ownership = ExecutionOwnership(execution_id, 1, "ab" * 64) + factory = Factory(replacement) + conn = open_connection(lost, factory, require_execution_ownership=True) + try: + cursor = conn.cursor() + cursor.execute("SELECT 1", ownership=ownership) + lost.drop() + error = outcome(cursor).error + assert isinstance(error, ConnectionLostError) + assert error.execution_id == execution_id + assert len(factory.calls) == 1 + assert not replacement.sent + replacement.socket.shutdown.assert_called_once() + finally: + conn.close() + + @pytest.mark.parametrize("server_generation", [None, 2]) def test_protected_terminal_event_requires_authenticated_result(server_generation): session = Session() session.subprotocol = OWNERSHIP_SUBPROTOCOL - public_key = "01" * 32 - execution_id = "owned_" + sha256(bytes.fromhex(public_key)).hexdigest() - ownership = ExecutionOwnership(execution_id, 1, "ab" * 64, public_key) + execution_id = "owned_" + "12" * 32 + ownership = ExecutionOwnership(execution_id, 1, "ab" * 64) conn = open_connection(session, Factory(), require_execution_ownership=True) try: cursor = conn.cursor() @@ -561,9 +574,8 @@ def test_protected_terminal_event_requires_authenticated_result(server_generatio def test_used_protected_id_carries_unknown_outcome(): session = Session() session.subprotocol = OWNERSHIP_SUBPROTOCOL - public_key = "01" * 32 - execution_id = "owned_" + sha256(bytes.fromhex(public_key)).hexdigest() - ownership = ExecutionOwnership(execution_id, 1, "ab" * 64, public_key) + execution_id = "owned_" + "12" * 32 + ownership = ExecutionOwnership(execution_id, 1, "ab" * 64) conn = open_connection(session, Factory(), require_execution_ownership=True) try: cursor = conn.cursor() @@ -583,18 +595,18 @@ def test_used_protected_id_carries_unknown_outcome(): @pytest.mark.parametrize( - ("generation", "signature", "public_key", "message"), + ("generation", "signature", "execution_id", "message"), [ - (True, "ab" * 64, "01" * 32, "generation"), - (1, "too short", "01" * 32, "signature"), - (1, "ab" * 64, "zz" * 32, "public key"), + (True, "ab" * 64, "owned_" + "12" * 32, "generation"), + (1, "too short", "owned_" + "12" * 32, "signature"), + (1, "ab" * 64, "invalid", "owned_ ID"), ], ) def test_malformed_ownership_is_rejected_before_sending( - generation, signature, public_key, message + generation, signature, execution_id, message ): with pytest.raises(ProgrammingError, match=message): - ExecutionOwnership("unused", generation, signature, public_key) + ExecutionOwnership(execution_id, generation, signature) # Giving up diff --git a/wherobots/db/connection.py b/wherobots/db/connection.py index 1be869a..681964b 100644 --- a/wherobots/db/connection.py +++ b/wherobots/db/connection.py @@ -719,7 +719,21 @@ def __open_transport( return None attempts += 1 try: - return factory(remaining) + ws = factory(remaining) + if ( + self.__require_execution_ownership + and ws.subprotocol != OWNERSHIP_SUBPROTOCOL + ): + try: + abort_connection(ws) + except Exception: + logging.debug( + "Could not abort unsupported SQL transport", exc_info=True + ) + raise InterfaceError( + "SQL session does not support execution ownership" + ) + return ws except InterfaceError as error: logging.error( "Could not reconnect to SQL session %s: %s", session, error @@ -1433,10 +1447,7 @@ def __execute_sql( if ownership is not None: if ownership.generation != 1: raise ProgrammingError("Protected submission requires generation 1") - request["ownership"] = { - **ownership.claim(), - "public_key": ownership.public_key, - } + request["ownership"] = ownership.claim() if self.__progress_handler is not None: request["enable_progress_events"] = True @@ -1518,8 +1529,6 @@ def __retrieve_request( request["attach"] = True if ownership is not None: request["ownership"] = ownership.claim() - if attach: - request["ownership"]["public_key"] = ownership.public_key return request def __request_results( diff --git a/wherobots/db/driver.py b/wherobots/db/driver.py index 8502467..5136499 100644 --- a/wherobots/db/driver.py +++ b/wherobots/db/driver.py @@ -432,7 +432,7 @@ def open_ws( ) -> websockets.sync.client.ClientConnection: _check_cancelled(cancel_event) logging.info("Connecting to SQL session at %s ...", uri_with_protocol) - ws = websockets.sync.client.connect( + return websockets.sync.client.connect( uri=uri_with_protocol, additional_headers=headers, max_size=MAX_MESSAGE_SIZE, @@ -450,10 +450,6 @@ def open_ws( else None ), ) - if require_execution_ownership and ws.subprotocol != OWNERSHIP_SUBPROTOCOL: - ws.close() - raise InterfaceError("SQL session does not support execution ownership") - return ws @tenacity.retry( stop=tenacity.stop_after_attempt(5), diff --git a/wherobots/db/models.py b/wherobots/db/models.py index 5796e8c..42ef221 100644 --- a/wherobots/db/models.py +++ b/wherobots/db/models.py @@ -1,5 +1,4 @@ from dataclasses import dataclass, field -from hashlib import sha256 import re from typing import Any, Dict @@ -17,7 +16,6 @@ class ExecutionOwnership: execution_id: str generation: int signature: str = field(repr=False) - public_key: str def __post_init__(self) -> None: if ( @@ -34,16 +32,11 @@ def __post_init__(self) -> None: raise ProgrammingError( "Ownership signature must contain 128 hex characters" ) - if not isinstance(self.public_key, str) or not re.fullmatch( - r"[0-9a-fA-F]{64}", self.public_key + if not isinstance(self.execution_id, str) or not re.fullmatch( + r"owned_[0-9a-f]{64}", self.execution_id ): raise ProgrammingError( - "Ownership public key must contain 64 hex characters" - ) - expected_id = "owned_" + sha256(bytes.fromhex(self.public_key)).hexdigest() - if self.execution_id != expected_id: - raise ProgrammingError( - "Execution ID does not match the ownership public key" + "Protected executions require an owned_ ID with 64 lowercase hex characters" ) def claim(self) -> dict[str, str | int]: From 5e0a82d3cdb871b4f1a8b684f2d65880a53d3b6a Mon Sep 17 00:00:00 2001 From: Clay McGinnis Date: Thu, 19 Nov 2026 20:47:30 -0800 Subject: [PATCH 3/4] test(dbapi): verify protected SQL error details --- tests/test_reconnect.py | 23 +++++++++++++++++++++++ wherobots/db/connection.py | 5 ++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/tests/test_reconnect.py b/tests/test_reconnect.py index 0fa4c18..5f2b5bd 100644 --- a/tests/test_reconnect.py +++ b/tests/test_reconnect.py @@ -571,6 +571,29 @@ def test_protected_terminal_event_requires_authenticated_result(server_generatio conn.close() +def test_protected_failed_query_reports_the_error_in_the_result_reply(): + session = Session() + session.subprotocol = OWNERSHIP_SUBPROTOCOL + execution_id = "owned_" + "12" * 32 + ownership = ExecutionOwnership(execution_id, 1, "ab" * 64) + conn = open_connection(session, Factory(), require_execution_ownership=True) + try: + cursor = conn.cursor() + cursor.execute("SELECT missing FROM t", ownership=ownership) + session.put(kind="state_updated", execution_id=execution_id, state="failed") + assert wait_until(lambda: session.requests("retrieve_results", execution_id)) + session.put( + kind="execution_result", + execution_id=execution_id, + state="failed", + exception_on_failure="Column missing does not exist", + ownership_generation=1, + ) + assert str(outcome(cursor).error) == "Column missing does not exist" + finally: + conn.close() + + def test_used_protected_id_carries_unknown_outcome(): session = Session() session.subprotocol = OWNERSHIP_SUBPROTOCOL diff --git a/wherobots/db/connection.py b/wherobots/db/connection.py index 681964b..d2d5493 100644 --- a/wherobots/db/connection.py +++ b/wherobots/db/connection.py @@ -1195,13 +1195,12 @@ def fail_attached(error: OperationalError) -> None: complete_query(ExecutionResult(results=pandas.DataFrame())) elif query.state == ExecutionState.FAILED: if query.ownership is not None and kind == EventKind.EXECUTION_RESULT: + # Protected SQL sessions include the cause in this reply. failure = ( message.get("exception_on_failure") or "SQL execution failed" ) fail_attached(OperationalError(failure)) - # Don't do anything here; the ERROR event is coming with more - # details. - pass + # Legacy sessions may send the details in a separate ERROR event. elif kind == EventKind.ERROR: error = message.get("message") not_found = error == _EXECUTION_NOT_FOUND From 8c7f70f6f366536f24c41d4f4a53b8adfd13d133 Mon Sep 17 00:00:00 2001 From: Clay McGinnis Date: Thu, 19 Nov 2026 20:51:44 -0800 Subject: [PATCH 4/4] fix(dbapi): abort transports that lack ownership support --- tests/test_driver.py | 4 +++- tests/test_reconnect.py | 16 ++++++++++++++++ wherobots/db/connection.py | 30 ++++++++++++++---------------- 3 files changed, 33 insertions(+), 17 deletions(-) diff --git a/tests/test_driver.py b/tests/test_driver.py index 363bd2f..0da90b8 100644 --- a/tests/test_driver.py +++ b/tests/test_driver.py @@ -563,7 +563,9 @@ def test_required_ownership_rejects_older_server_before_submission(self, mock_ws "wherobots.execution-ownership.v1" ] assert not mock_ws.call_args.kwargs["logger"].isEnabledFor(logging.DEBUG) - ws.close.assert_called_once() + ws.socket.shutdown.assert_called_once() + ws.socket.close.assert_called_once() + ws.close.assert_not_called() ws.send.assert_not_called() @patch("wherobots.db.driver.websockets.sync.client.connect") diff --git a/tests/test_reconnect.py b/tests/test_reconnect.py index 5f2b5bd..267e9d1 100644 --- a/tests/test_reconnect.py +++ b/tests/test_reconnect.py @@ -508,6 +508,22 @@ def test_protected_reconnect_preserves_claim_without_replaying_sql(caplog): conn.close() +def test_protected_connection_aborts_an_unsupported_transport(): + session = Session() + session.subprotocol = None + session.close_timeout = None + session.socket.shutdown.side_effect = None + with ( + patch.object(session, "close", side_effect=AssertionError("unbounded close")), + pytest.raises(InterfaceError, match="does not support execution ownership"), + ): + open_connection(session, Factory(), require_execution_ownership=True) + + session.socket.shutdown.assert_called_once() + session.socket.close.assert_called_once() + assert not session.sent + + def test_protected_reconnect_rejects_a_replacement_without_ownership_support(): lost, replacement = Session(), Session() lost.subprotocol = OWNERSHIP_SUBPROTOCOL diff --git a/wherobots/db/connection.py b/wherobots/db/connection.py index d2d5493..5dd7cda 100644 --- a/wherobots/db/connection.py +++ b/wherobots/db/connection.py @@ -60,6 +60,16 @@ class _TransportError(Exception): """An I/O failure raised while receiving from the WebSocket.""" +def _require_ownership_subprotocol(ws: websockets.sync.client.ClientConnection) -> None: + if ws.subprotocol == OWNERSHIP_SUBPROTOCOL: + return + try: + abort_connection(ws) + except Exception: + logging.debug("Could not abort unsupported SQL transport", exc_info=True) + raise InterfaceError("SQL session does not support execution ownership") + + _READER_JOIN_SECONDS = 1.0 """How long close() waits for the reader thread once teardown has finished.""" @@ -318,9 +328,8 @@ def __init__( :param session_key_exclusive: See :attr:`session_key_exclusive`. """ self.__ws = ws - if require_execution_ownership and ws.subprotocol != OWNERSHIP_SUBPROTOCOL: - ws.close() - raise InterfaceError("SQL session does not support execution ownership") + if require_execution_ownership: + _require_ownership_subprotocol(ws) self.__require_execution_ownership = require_execution_ownership self.__transport_factory = transport_factory self.__reconnect_within = ( @@ -720,19 +729,8 @@ def __open_transport( attempts += 1 try: ws = factory(remaining) - if ( - self.__require_execution_ownership - and ws.subprotocol != OWNERSHIP_SUBPROTOCOL - ): - try: - abort_connection(ws) - except Exception: - logging.debug( - "Could not abort unsupported SQL transport", exc_info=True - ) - raise InterfaceError( - "SQL session does not support execution ownership" - ) + if self.__require_execution_ownership: + _require_ownership_subprotocol(ws) return ws except InterfaceError as error: logging.error(