Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions tests/test_driver.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Tests for the connect() and connect_direct() driver functions."""

import logging
import threading
import time
from importlib import metadata
Expand Down Expand Up @@ -545,6 +546,28 @@ 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.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")
def test_close_handshake_is_bounded(self, mock_ws):
from websockets.exceptions import ConnectionClosedOK
Expand Down
170 changes: 170 additions & 0 deletions tests/test_reconnect.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,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
Expand Down Expand Up @@ -478,6 +482,172 @@ 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
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()
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()
assert again.sent[1]["ownership"] == ownership.claim()
assert not again.requests("execute_sql")
assert ownership.signature not in caplog.text
finally:
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
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
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 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_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
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 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", "execution_id", "message"),
[
(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, execution_id, message
):
with pytest.raises(ProgrammingError, match=message):
ExecutionOwnership(execution_id, generation, signature)


# Giving up


Expand Down
5 changes: 4 additions & 1 deletion wherobots/db/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -32,6 +33,8 @@
"ConnectionLostError",
"ExecutionCancelledError",
"ExecutionNotFoundError",
"ExecutionOwnership",
"ExecutionOwnershipError",
"ProgrammingError",
"NotSupportedError",
"Region",
Expand Down
Loading
Loading