diff --git a/.github/workflows/sdks-python-test.yml b/.github/workflows/sdks-python-test.yml index e1c233dd..168d4deb 100644 --- a/.github/workflows/sdks-python-test.yml +++ b/.github/workflows/sdks-python-test.yml @@ -34,6 +34,15 @@ jobs: sudo apt-get update sudo apt-get install -y protobuf-compiler + # The end-to-end tests build and run the real agent. + - name: Set up Go + uses: actions/setup-go@v3 + with: + go-version: '1.26.10' + + - name: Generate agent protobuf + run: make -C agent setup proto + - name: Run Linter run: | cd sdks/python diff --git a/sdks/python/README.md b/sdks/python/README.md index ba821ae3..b42c503d 100644 --- a/sdks/python/README.md +++ b/sdks/python/README.md @@ -106,3 +106,64 @@ client = AxonClient(scope=globals(), max_concurrent_handlers=16) ``` Set it to `1` for the old behaviour, where handlers run one at a time. + +## Failure hooks + +Pass `on_failure` to `AxonClient` to run your own code whenever an +invocation fails, for example to send the failed message somewhere you can +replay it from. Every failure goes through the agent, wherever it happened: +a handler that raised in this process, or a webhook the agent couldn't hand +to this process because every handler was busy. The agent sends each one to +your hook and does what the hook returns. Failures arrive on their own +stream, so they get through even while every handler slot is taken, and a +failure your hook hadn't answered when the connection dropped is sent again. +This needs an agent that supports failure events. + +```python +from cortex_axon import AxonClient, FailureAction, FailureSource +from cortex_axon.handler import cortex_webhook + + +@cortex_webhook(id="my-webhook-1") +def my_webhook_handler(context): + process(context.args["body"]) + + +def on_failure(info, failure): + # info.args holds the original webhook: "body", "content-type", "url" + dead_letters.publish({ + "handler": info.handler_name, + "invocation_id": info.invocation_id, + "attempt": info.attempt, + "reason": failure.reason.name, # HANDLER_ERROR, TIMEOUT, NO_RESOURCES + "source": failure.source.name, # APPLICATION or RUNTIME + "caller_rejected": failure.caller_rejected, + "message": info.args, + }) + # Optionally have the agent run it again, as a new attempt. + if failure.source == FailureSource.RUNTIME and info.attempt < 3: + return FailureAction.RETRY + + +client = AxonClient(scope=globals(), on_failure=on_failure) +client.run() +``` + +| Reason | When | Source | +|---|---|---| +| `HANDLER_ERROR` | The handler raised | `APPLICATION` | +| `TIMEOUT` | The handler ran past its timeout | `RUNTIME` if a Cortex API call was in flight, the invocation waited for a free handler, or the agent never got a result; otherwise `APPLICATION` | +| `NO_RESOURCES` | The agent's queue was full, or the message expired waiting for a free handler | `RUNTIME` | + +`caller_rejected` is true when the sender was told the message wasn't +accepted (a webhook got a 503), so the sender may also retry it. + +Returning `FailureAction.RETRY` has the agent queue the invocation again, +with `attempt` incremented; it stops after 5 attempts. Returning +`FailureAction.DROP`, or nothing, drops it. If the hook raises, the +invocation is dropped. + +The hook runs for every handler type, not only webhooks. Python can't stop a +handler that overruns its timeout: at the deadline the SDK reports the +`TIMEOUT` and runs the hook, and whatever the handler does after that is +dropped. diff --git a/sdks/python/cortex_axon/__init__.py b/sdks/python/cortex_axon/__init__.py index 8bafa392..f31cadd4 100644 --- a/sdks/python/cortex_axon/__init__.py +++ b/sdks/python/cortex_axon/__init__.py @@ -1,2 +1,7 @@ from .axon_client import AxonClient as AxonClient from .axon_client import CortexHTTPError as CortexHTTPError +from .hooks import Failure as Failure +from .hooks import FailureAction as FailureAction +from .hooks import FailureReason as FailureReason +from .hooks import FailureSource as FailureSource +from .hooks import InvocationInfo as InvocationInfo diff --git a/sdks/python/cortex_axon/axon_client.py b/sdks/python/cortex_axon/axon_client.py index e92c0650..34804fbb 100644 --- a/sdks/python/cortex_axon/axon_client.py +++ b/sdks/python/cortex_axon/axon_client.py @@ -5,7 +5,7 @@ import traceback from concurrent.futures import ThreadPoolExecutor from datetime import datetime -from time import monotonic, sleep +from time import monotonic, sleep, time from typing import Any, Optional from urllib.parse import quote_plus @@ -24,8 +24,36 @@ CortexAnnotation, find_annotated_methods, ) +from .hooks import ( + Failure, + FailureAction, + FailureHook, + FailureReason, + FailureSource, + InvocationInfo, +) DEFAULT_MAX_CONCURRENT_HANDLERS = 8 +RECONNECT_WAIT_SECONDS = 5 +# How far ahead of the agent's deadline a handler must finish, so its report +# reaches the agent before the agent gives up on it. +DEADLINE_MARGIN_SECONDS = 1.0 + + +def _invoke_timeout(invoke, now: float): + """How long a handler may run, in seconds (None for no limit): its own + timeout, but no later than the agent's deadline. capped means the agent's + deadline is the tighter one, i.e. the invocation waited before it got + here. expired means it is already too late to start.""" + timeout = invoke.timeout_ms / 1000 if invoke.timeout_ms > 0 else None + if not invoke.HasField("deadline"): + return timeout, False, False + remaining = invoke.deadline.ToMicroseconds() / 1e6 - now - DEADLINE_MARGIN_SECONDS + if remaining <= 0: + return None, False, True + if timeout is None or remaining < timeout: + return remaining, True, False + return timeout, False, False # TODO Add docstrings @@ -152,6 +180,7 @@ def __init__( scope=None, max_receive_message_size: Optional[int] = None, max_concurrent_handlers: int = DEFAULT_MAX_CONCURRENT_HANDLERS, + on_failure: Optional[FailureHook] = None, ): if max_concurrent_handlers < 1: raise ValueError("max_concurrent_handlers must be at least 1") @@ -196,6 +225,19 @@ def __init__( ) self._handler_slots = threading.BoundedSemaphore(max_concurrent_handlers) + self.on_failure = on_failure + # Failure events have their own thread and pool, apart from the + # handler slots: they arrive exactly when every handler is busy, and + # must never wait for one to free up. + self._hook_executor = None + self._events_thread = None + self._events_stop = threading.Event() + self._events_call = None + if on_failure: + self._hook_executor = ThreadPoolExecutor( + max_workers=2, thread_name_prefix="axon-hook" + ) + def _get_stub(self): if not self.agent_stub: self.agent_channel = grpc.insecure_channel( @@ -231,7 +273,79 @@ def _find_handler(self, name): return h return None - def _handler_context(self, args, timeout_ms: int = 0): + def _run_failure_hook(self, info: InvocationInfo, failure: Failure) -> FailureAction: + try: + action = self.on_failure(info, failure) + except Exception: + print(f"Error in on_failure hook for {info.handler_name} (id={info.invocation_id}), dropping it") + traceback.print_exc() + return FailureAction.DROP + return action or FailureAction.DROP + + def _answer_failure(self, event, answers: queue.Queue): + info = InvocationInfo.from_proto(event.invoke) + action = self._run_failure_hook(info, Failure.from_proto(event.failure)) + answers.put(cortex_axon_agent_pb2.DispatchEventsRequest( + resolution=cortex_axon_agent_pb2.FailureResolution( + invocation_id=info.invocation_id, + action=action.to_proto(), + ) + )) + + def _start_failure_events(self): + if not self.on_failure or self._events_thread: + return + self._events_thread = threading.Thread( + target=self._run_failure_events, name="axon-failure-events", daemon=True + ) + self._events_thread.start() + + def _stop_failure_events(self): + self._events_stop.set() + call = self._events_call + if call: + call.cancel() + + def _run_failure_events(self): + # A channel of its own, so the dispatch loop resetting its channel + # after an error doesn't cut this stream too. + channel = grpc.insecure_channel( + self.agent_hostport, options=self.grpc_channel_options + ) + stub = cortex_axon_agent_pb2_grpc.AxonAgentStub(channel) + try: + while not self._events_stop.is_set(): + # Answers for this stream only: one the agent never got is + # sent again on the next stream, and answered there. + answers = queue.Queue() + + def requests(answers=answers): + yield cortex_axon_agent_pb2.DispatchEventsRequest( + dispatch_id=self.id, client_version=AGENT_VERSION + ) + while (answer := answers.get()) is not None: + yield answer + + try: + self._events_call = stub.DispatchEvents(requests()) + for event in self._events_call: + if not event.HasField("invoke"): + continue + self._hook_executor.submit(self._answer_failure, event, answers) + except grpc.RpcError as e: + if self._events_stop.is_set(): + return + if e.code() == grpc.StatusCode.UNIMPLEMENTED: + print("Agent does not send failure events, upgrade the agent to use on_failure") + return + print(f"Failure event stream ended ({e.code()}), reconnecting in {RECONNECT_WAIT_SECONDS} seconds...") + finally: + answers.put(None) + self._events_stop.wait(RECONNECT_WAIT_SECONDS) + finally: + channel.close() + + def _handler_context(self, args, timeout_ms: float = 0): return HandlerContext(self.cortex_stub, args, timeout_ms) def _submit_handler(self, handler_to_invoke, invoke): @@ -239,6 +353,16 @@ def _submit_handler(self, handler_to_invoke, invoke): # sees its own queue fill rather than this process growing without # bound, and the dispatch stream stays readable up to that point. self._handler_slots.acquire() + _, _, expired = _invoke_timeout(invoke, time()) + if expired: + # The agent has already reported this one as failed; running it + # now would duplicate work a failure hook may be replaying. + self._handler_slots.release() + print( + f"Dispatch handler SKIPPED {invoke.handler_name} (id={invoke.invocation_id}): " + "expired while waiting for a free handler" + ) + return stub = self.agent_stub try: future = self._executor.submit( @@ -255,11 +379,54 @@ def _invoke_handler(self, handler_to_invoke, invoke, stub): ) handler_err = None handler_result = None + failure = None result = None now = datetime.now() - ctx = self._handler_context(invoke.args, invoke.timeout_ms) + timeout, capped, _ = _invoke_timeout(invoke, time()) + ctx = self._handler_context(invoke.args, timeout * 1000 if timeout else 0) duration_ms = 0 + # A Python thread can't be stopped, so at the deadline the timer + # reports the timeout itself and the handler's eventual result is + # dropped. Whichever finishes first claims the invocation. + finish_lock = threading.Lock() + finished = False + + def claim(): + nonlocal finished + with finish_lock: + if finished: + return False + finished = True + return True + + def on_timeout(): + if not claim(): + return + source = FailureSource.APPLICATION + message = f"handler did not finish within {invoke.timeout_ms}ms" + if ctx.blocked_on_api(): + source = FailureSource.RUNTIME + message += " while waiting on a Cortex API call" + elif capped: + source = FailureSource.RUNTIME + message = "invocation waited for a free handler and ran out of time" + print(f"Dispatch handler TIMEOUT {invoke.handler_name} (id={invoke.invocation_id}): {message}") + self._report(stub, cortex_axon_agent_pb2.ReportInvocationRequest( + handler_invoke=invoke, + start_client_timestamp=now, + duration_ms=invoke.timeout_ms, + error=common_pb2.Error(code="timeout", message=message), + failure=Failure(reason=FailureReason.TIMEOUT, source=source, message=message).to_proto(), + logs=list(ctx.logs), + )) + + timer = None + if timeout: + timer = threading.Timer(timeout, on_timeout) + timer.daemon = True + timer.start() + try: result = handler_to_invoke(ctx) duration_ms = int( @@ -276,6 +443,24 @@ def _invoke_handler(self, handler_to_invoke, invoke, stub): handler_err = common_pb2.Error( code="unexpected", message="Error calling handler: " + str(e) ) + if ctx.blocked_on_api(): + failure = Failure( + reason=FailureReason.TIMEOUT, + source=FailureSource.RUNTIME, + message=f"Cortex API call did not finish within the {invoke.timeout_ms}ms timeout: {e}", + ) + else: + failure = Failure( + reason=FailureReason.HANDLER_ERROR, + source=FailureSource.APPLICATION, + message=str(e), + ) + + if timer: + timer.cancel() + if not claim(): + print(f"Dispatch handler {invoke.handler_name} (id={invoke.invocation_id}) finished after its timeout, result dropped") + return invoke_info = cortex_axon_agent_pb2.ReportInvocationRequest( handler_invoke=invoke, @@ -283,27 +468,38 @@ def _invoke_handler(self, handler_to_invoke, invoke, stub): duration_ms=duration_ms, result=handler_result, error=handler_err, + # The agent sends the failure back to on_failure, so it is + # handled the same way as failures only the agent can see. + failure=failure.to_proto() if failure else None, logs=ctx.logs, ) + self._report(stub, invoke_info) + + def _report(self, stub, invoke_info): # A failure here must not escape the worker: the dispatch loop is no # longer in the call path, so an exception would be swallowed by the # future and the invocation would look like it vanished. try: report_response = stub.ReportInvocation(invoke_info) + if report_response.error and report_response.error.code: + print( + f"Error reporting invocation: {report_response.error}" + ) except Exception as e: print( - f"Error reporting invocation {invoke.invocation_id}: {e}" + f"Error reporting invocation {invoke_info.handler_invoke.invocation_id}: {e}" ) traceback.print_exc() - return - - if report_response.error and report_response.error.code: - print( - f"Error reporting invocation: {report_response.error}" - ) def run(self): + self._start_failure_events() + try: + self._run_dispatch() + finally: + self._stop_failure_events() + + def _run_dispatch(self): registered = False while True: stub = self._get_stub() @@ -314,7 +510,8 @@ def run(self): initial_message = cortex_axon_agent_pb2.DispatchRequest( dispatch_id=self.id, - client_version=AGENT_VERSION + client_version=AGENT_VERSION, + failure_events=self.on_failure is not None, ) for response in stub.Dispatch( _client_message_iterator(initial_message) @@ -364,6 +561,14 @@ def __init__(self, api: cortex_api_pb2_grpc.CortexApiStub, args: dict, timeout_m # worker after the agent has given up on the invocation, and once # every worker is held the client stops taking new invocations. self.deadline = monotonic() + timeout_ms / 1000 if timeout_ms > 0 else None + # Whether a Cortex API call was running, or ran out of time, when the + # deadline hit, which makes the timeout Axon's fault rather than the + # handler's. + self._api_in_flight = 0 + self._api_timed_out = False + + def blocked_on_api(self) -> bool: + return self._api_in_flight > 0 or self._api_timed_out def log(self, message: str, level="INFO"): """ @@ -395,5 +600,15 @@ def cortex_api_call( timeout = None if self.deadline is not None: timeout = max(self.deadline - monotonic(), 0) - response = self.api.Call(request, timeout=timeout) + self._api_in_flight += 1 + try: + response = self.api.Call(request, timeout=timeout) + except grpc.RpcError as e: + if e.code() == grpc.StatusCode.DEADLINE_EXCEEDED: + # Set before _api_in_flight drops, so a timeout check never + # sees neither. + self._api_timed_out = True + raise + finally: + self._api_in_flight -= 1 return CortexResponse(response.status_code, response.body, response.headers) diff --git a/sdks/python/cortex_axon/hooks.py b/sdks/python/cortex_axon/hooks.py new file mode 100644 index 00000000..d9d57cb7 --- /dev/null +++ b/sdks/python/cortex_axon/hooks.py @@ -0,0 +1,95 @@ +from dataclasses import dataclass, field +from enum import Enum, IntEnum +from typing import Any, Callable, Optional + +from generated import cortex_axon_agent_pb2 + + +class FailureReason(IntEnum): + UNSPECIFIED = cortex_axon_agent_pb2.FAILURE_REASON_UNSPECIFIED + # The handler raised. + HANDLER_ERROR = cortex_axon_agent_pb2.HANDLER_ERROR + # The invocation did not finish within its timeout. + TIMEOUT = cortex_axon_agent_pb2.TIMEOUT + # The invocation never ran: the agent's queue was full, or it expired + # waiting for a free handler. + NO_RESOURCES = cortex_axon_agent_pb2.NO_RESOURCES + + +class FailureSource(IntEnum): + UNSPECIFIED = cortex_axon_agent_pb2.FAILURE_SOURCE_UNSPECIFIED + # Handler code failed. + APPLICATION = cortex_axon_agent_pb2.APPLICATION + # Axon failed: the agent, the SDK, or a Cortex API call. + RUNTIME = cortex_axon_agent_pb2.RUNTIME + + +class FailureAction(Enum): + # Do nothing more with the invocation. + DROP = "drop" + # Have the agent queue the invocation again as its next attempt. + RETRY = "retry" + + def to_proto(self) -> int: + if self == FailureAction.RETRY: + return cortex_axon_agent_pb2.FAILURE_ACTION_RETRY + return cortex_axon_agent_pb2.FAILURE_ACTION_DROP + + +@dataclass(frozen=True) +class InvocationInfo: + """Identifies one invocation. For a webhook, args holds the inbound + message: "body", "content-type" and "url".""" + + invocation_id: str + handler_name: str + invoke_type: int + args: dict[str, str] + # 1 for the first delivery, counting up with each retry. + attempt: int + invoke: Any = field(repr=False, compare=False) + + @classmethod + def from_proto(cls, invoke: cortex_axon_agent_pb2.DispatchHandlerInvoke) -> "InvocationInfo": + return cls( + invocation_id=invoke.invocation_id, + handler_name=invoke.handler_name, + invoke_type=invoke.reason, + args=dict(invoke.args), + attempt=max(invoke.attempt, 1), + invoke=invoke, + ) + + +@dataclass(frozen=True) +class Failure: + reason: FailureReason + source: FailureSource + message: str + # Whoever sent the invocation was told it was not accepted (a webhook + # sender got a 503), so it may arrive again. + caller_rejected: bool = False + + def to_proto(self) -> cortex_axon_agent_pb2.InvocationFailure: + return cortex_axon_agent_pb2.InvocationFailure( + reason=self.reason, + source=self.source, + message=self.message, + caller_rejected=self.caller_rejected, + ) + + @classmethod + def from_proto(cls, failure: cortex_axon_agent_pb2.InvocationFailure) -> "Failure": + return cls( + reason=FailureReason(failure.reason), + source=FailureSource(failure.source), + message=failure.message, + caller_rejected=failure.caller_rejected, + ) + + +# Runs for every failed invocation, wherever it failed: in this process, or in +# the agent, such as an invocation that never reached this process. The agent +# sends each failure here and applies the answer. Returning None means +# FailureAction.DROP. +FailureHook = Callable[[InvocationInfo, Failure], Optional[FailureAction]] diff --git a/sdks/python/example/main.py b/sdks/python/example/main.py index 826e7b4c..e03c87a0 100644 --- a/sdks/python/example/main.py +++ b/sdks/python/example/main.py @@ -1,5 +1,6 @@ import json +from cortex_axon import FailureAction from cortex_axon.axon_client import AxonClient, HandlerContext from cortex_axon.handler import cortex_handler, cortex_scheduled @@ -50,10 +51,23 @@ def my_invoke_handler(context: HandlerContext) -> str: return json.dumps(result) +def on_failure(info, failure): + # Runs for every failed invocation, including ones only the agent sees. + print( + f"FAILED {info.handler_name} (id={info.invocation_id}, attempt={info.attempt}) " + f"reason={failure.reason.name} source={failure.source.name}: {failure.message}" + ) + # A real hook would save info.args somewhere it can be replayed from. + if info.attempt < 3: + return FailureAction.RETRY + return FailureAction.DROP + + def run(): # Connect to the gRPC server client = AxonClient( scope=globals(), + on_failure=on_failure, ) client.run() diff --git a/sdks/python/tests/test_e2e_failures.py b/sdks/python/tests/test_e2e_failures.py new file mode 100644 index 00000000..148734cb --- /dev/null +++ b/sdks/python/tests/test_e2e_failures.py @@ -0,0 +1,248 @@ +"""The SDK against a real agent, triggered through the agent's webhook +endpoint. The agent is built from ../../agent with `go`, or taken from +AXON_AGENT_BIN; without either these tests are skipped.""" + +import collections +import os +import queue +import shutil +import socket +import subprocess +import threading +import time +import urllib.error +import urllib.request +from pathlib import Path + +import pytest + +from cortex_axon import AxonClient, FailureAction, FailureReason, FailureSource +from cortex_axon.handler import CortexWebhook + +AGENT_DIR = Path(__file__).resolve().parents[3] / "agent" + +# AxonClient.run has no way to stop, so a test's client keeps retrying after +# its agent is killed, and may print into pytest's closed capture. +pytestmark = pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning") + + +@pytest.fixture(scope="session") +def agent_bin(tmp_path_factory): + if os.environ.get("AXON_AGENT_BIN"): + return os.environ["AXON_AGENT_BIN"] + if not shutil.which("go"): + pytest.skip("needs go to build the agent, or AXON_AGENT_BIN") + out = tmp_path_factory.mktemp("agent") / "axon-agent" + subprocess.run(["go", "build", "-o", str(out), "."], cwd=AGENT_DIR, check=True) + return str(out) + + +def free_ports(n): + """Return n distinct free ports, holding each open until all are picked.""" + socks = [socket.socket() for _ in range(n)] + try: + for s in socks: + s.bind(("127.0.0.1", 0)) + return [s.getsockname()[1] for s in socks] + finally: + for s in socks: + s.close() + + +class RealAgent: + def __init__(self, agent_bin, tmp_path): + self.grpc_port, self.webhook_port, http_port = free_ports(3) + env = dict( + os.environ, + DRYRUN="true", + PORT=str(self.grpc_port), + HTTP_PORT=str(http_port), + WEBHOOK_PORT=str(self.webhook_port), + HANDLER_HISTORY_PATH=str(tmp_path / "history"), + ) + # Stays open for the agent process's lifetime; closed in stop(). + self.log = open(tmp_path / "agent.log", "wb") # noqa: SIM115 + self.proc = subprocess.Popen( + [agent_bin, "serve"], env=env, stdout=self.log, stderr=subprocess.STDOUT + ) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + try: + socket.create_connection(("127.0.0.1", self.grpc_port), timeout=0.2).close() + return + except OSError: + time.sleep(0.05) + raise AssertionError("agent never started listening") + + def post(self, webhook_id, body): + """Sends body once the webhook is live; returns the HTTP status.""" + url = f"http://127.0.0.1:{self.webhook_port}/webhook/{webhook_id}" + deadline = time.monotonic() + 10 + while True: + req = urllib.request.Request(url, data=body.encode(), method="POST", + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req) as r: + return r.status + except urllib.error.HTTPError as e: + # 404 until the SDK has registered and started dispatching. + if e.code != 404 or time.monotonic() > deadline: + return e.code + time.sleep(0.05) + + def stop(self): + self.proc.kill() + self.proc.wait() + self.log.close() + + +@pytest.fixture +def real_agent(agent_bin, tmp_path): + agent = RealAgent(agent_bin, tmp_path) + yield agent + agent.stop() + + +class Recorder: + """Records each run of the handler and each call of the failure hook, + which always asks for a retry.""" + + def __init__(self): + self.lock = threading.Lock() + self.runs = collections.Counter() + self.succeeded = collections.Counter() + self.failures = [] + self.failure_seen = queue.Queue() + self.success_seen = queue.Queue() + + def ran(self, ctx): + with self.lock: + self.runs[ctx.args["body"]] += 1 + return self.runs[ctx.args["body"]] + + def ok(self, ctx): + with self.lock: + self.succeeded[ctx.args["body"]] += 1 + self.success_seen.put(ctx.args["body"]) + + def on_failure(self, info, failure): + with self.lock: + self.failures.append((info, failure)) + self.failure_seen.put((info, failure)) + return FailureAction.RETRY + + +def run_client(agent, recorder, webhook_id, func, timeout_ms=0, slots=4): + webhook = CortexWebhook(id=webhook_id, timeout_ms=timeout_ms) + webhook.set_func(func) + client = AxonClient( + agent_host="127.0.0.1", + agent_port=agent.grpc_port, + handlers=[webhook], + max_concurrent_handlers=slots, + on_failure=recorder.on_failure, + ) + threading.Thread(target=client.run, daemon=True).start() + return client + + +def test_handler_error_is_hooked_and_retried(real_agent): + rec = Recorder() + + def e2e_error(ctx): + if rec.ran(ctx) == 1: + raise ValueError("first attempt fails") + rec.ok(ctx) + + run_client(real_agent, rec, "e2e-error", e2e_error) + assert real_agent.post("e2e-error", '{"id": 42}') == 200 + + info, failure = rec.failure_seen.get(timeout=15) + assert failure.reason == FailureReason.HANDLER_ERROR + assert failure.source == FailureSource.APPLICATION + assert failure.message == "first attempt fails" + assert info.args["body"] == '{"id": 42}' + assert info.attempt == 1 + + # The retry carries the original message, and succeeds. + assert rec.success_seen.get(timeout=15) == '{"id": 42}' + with pytest.raises(queue.Empty): + rec.failure_seen.get(timeout=1) + assert rec.runs['{"id": 42}'] == 2 + + +def test_timeout_is_hooked_and_retried(real_agent): + rec = Recorder() + + def e2e_timeout(ctx): + if rec.ran(ctx) == 1: + time.sleep(3) + return + rec.ok(ctx) + + run_client(real_agent, rec, "e2e-timeout", e2e_timeout, timeout_ms=500) + assert real_agent.post("e2e-timeout", '{"id": 7}') == 200 + + info, failure = rec.failure_seen.get(timeout=15) + assert failure.reason == FailureReason.TIMEOUT + assert failure.source == FailureSource.APPLICATION + assert info.args["body"] == '{"id": 7}' + + assert rec.success_seen.get(timeout=15) == '{"id": 7}' + + # The SDK reported the timeout itself, so the agent must not report it + # again once its grace period is over, and the late finish is dropped. + with pytest.raises(queue.Empty): + rec.failure_seen.get(timeout=7) + assert rec.succeeded['{"id": 7}'] == 1 + + +def test_saturated_invocations_are_hooked_retried_and_run_once(real_agent): + """One handler slot, stuck. The invocations queued behind it expire; the + agent reports them, the hook retries them, and each message ends up + succeeding exactly once. None of the expired originals runs late.""" + rec = Recorder() + release = threading.Event() + bodies = [f"m{i}" for i in range(5)] + + def e2e_busy(ctx): + rec.ran(ctx) + if not release.is_set(): + release.wait(30) + return + rec.ok(ctx) + + original_hook = rec.on_failure + + def on_failure(info, failure): + if failure.source == FailureSource.RUNTIME: + # The agent has given up on the queued ones: unstick the slot. + release.set() + return original_hook(info, failure) + + rec.on_failure = on_failure + run_client(real_agent, rec, "e2e-busy", e2e_busy, timeout_ms=1000, slots=1) + + assert real_agent.post("e2e-busy", bodies[0]) == 200 + for body in bodies[1:]: + assert real_agent.post("e2e-busy", body) == 200 + + succeeded = {rec.success_seen.get(timeout=30) for _ in bodies} + assert succeeded == set(bodies) + with pytest.raises(queue.Empty): + rec.success_seen.get(timeout=2) + + with rec.lock: + assert all(rec.succeeded[b] == 1 for b in bodies), rec.succeeded + # Each failure is reported once per invocation. + ids = [info.invocation_id for info, _ in rec.failures] + assert len(ids) == len(set(ids)), "an invocation was reported twice" + # Every message failed at least once, and the queued ones were + # reported by the agent as Axon's fault. + failed = collections.Counter(info.args["body"] for info, _ in rec.failures) + assert set(failed) == set(bodies) + runtime = {info.args["body"] for info, f in rec.failures if f.source == FailureSource.RUNTIME} + assert set(bodies[1:]) <= runtime + # The expired originals never ran: each queued message ran once, as + # its retry. + assert all(rec.runs[b] == 1 for b in bodies[1:]), rec.runs diff --git a/sdks/python/tests/test_hooks.py b/sdks/python/tests/test_hooks.py new file mode 100644 index 00000000..759612b1 --- /dev/null +++ b/sdks/python/tests/test_hooks.py @@ -0,0 +1,384 @@ +import contextlib +import queue +import threading +import time +from concurrent.futures import ThreadPoolExecutor + +import grpc +import pytest + +from cortex_axon import ( + AxonClient, + FailureAction, + FailureReason, + FailureSource, +) +from cortex_axon.handler import CortexWebhook +from generated import ( + common_pb2, + cortex_api_pb2_grpc, + cortex_axon_agent_pb2, + cortex_axon_agent_pb2_grpc, +) + +HANDLER = "my_hooked_webhook" + + +class HookAgent(cortex_axon_agent_pb2_grpc.AxonAgentServicer): + """Sends a fixed set of invocations and failure events, then holds both + streams open, recording what the client sends back.""" + + def __init__(self, invokes=(), events=(), events_code=None): + self.invokes = list(invokes) + self.events = list(events) + self.events_code = events_code + self.dispatch_requests = queue.Queue() + self.events_requests = queue.Queue() + self.resolutions = queue.Queue() + self.events_calls = 0 + self.reports = queue.Queue() + self.stop = threading.Event() + + def RegisterHandler(self, request, context): + return cortex_axon_agent_pb2.RegisterHandlerResponse( + error=common_pb2.Error(code="0", message="OK"), + id=request.dispatch_id, + ) + + def Dispatch(self, request_iterator, context): + request = next(request_iterator) + self.dispatch_requests.put(request) + for invoke in self.invokes: + yield cortex_axon_agent_pb2.DispatchMessage( + type=cortex_axon_agent_pb2.DISPATCH_MESSAGE_INVOKE, + invoke=invoke, + ) + self.invokes = [] + self.stop.wait(timeout=10) + + def DispatchEvents(self, request_iterator, context): + self.events_calls += 1 + if self.events_code: + context.abort(self.events_code, "not here") + self.events_requests.put(next(request_iterator)) + + def read_answers(): + # Ends with an error when the client goes away at teardown. + with contextlib.suppress(Exception): + for request in request_iterator: + if request.HasField("resolution"): + self.resolutions.put(request.resolution) + + threading.Thread(target=read_answers, daemon=True).start() + events, self.events = self.events, [] + yield from events + self.stop.wait(timeout=10) + + def ReportInvocation(self, request, context): + self.reports.put(request) + return cortex_axon_agent_pb2.ReportInvocationResponse() + + +class SlowApi(cortex_api_pb2_grpc.CortexApiServicer): + def __init__(self): + self.release = threading.Event() + + def Call(self, request, context): + self.release.wait(timeout=10) + context.abort(grpc.StatusCode.UNAVAILABLE, "too late") + + +def invoke(invocation_id="1", timeout_ms=0, deadline_in=None, **args): + msg = cortex_axon_agent_pb2.DispatchHandlerInvoke( + invocation_id=invocation_id, + handler_id=HANDLER, + handler_name=HANDLER, + reason=cortex_axon_agent_pb2.WEBHOOK, + timeout_ms=timeout_ms, + args=args, + ) + if deadline_in is not None: + msg.deadline.FromMicroseconds(int((time.time() + deadline_in) * 1e6)) + return msg + + +def failure_event(invocation_id, attempt=1, **args): + msg = invoke(invocation_id, **args) + msg.attempt = attempt + return cortex_axon_agent_pb2.DispatchEvent( + invoke=msg, + failure=cortex_axon_agent_pb2.InvocationFailure( + reason=cortex_axon_agent_pb2.NO_RESOURCES, + source=cortex_axon_agent_pb2.RUNTIME, + message="dispatch queue is full", + caller_rejected=True, + ), + ) + + +def serve(servicer, add): + server = grpc.server(ThreadPoolExecutor(max_workers=8)) + port = server.add_insecure_port("127.0.0.1:0") + add(servicer, server) + server.start() + return server, port + + +class Hooks: + def __init__(self, action=None): + self.action = action + self.failures = queue.Queue() + + def on_failure(self, info, failure): + self.failures.put((info, failure)) + return self.action + + +@pytest.fixture +def run_client(): + servers = [] + agents = [] + clients = [] + + def start(agent, handler, hooks=None, api=None, max_concurrent_handlers=4): + server, port = serve(agent, cortex_axon_agent_pb2_grpc.add_AxonAgentServicer_to_server) + servers.append(server) + agents.append(agent) + api_port = port + if api: + api_server, api_port = serve(api, cortex_api_pb2_grpc.add_CortexApiServicer_to_server) + servers.append(api_server) + + webhook = CortexWebhook(id="hook") + webhook.set_func(handler) + client = AxonClient( + agent_host="127.0.0.1", + agent_port=port, + cortex_host="127.0.0.1", + cortex_port=api_port, + handlers=[webhook], + max_concurrent_handlers=max_concurrent_handlers, + on_failure=hooks.on_failure if hooks else None, + ) + threading.Thread(target=client.run, daemon=True).start() + clients.append(client) + return client + + yield start + for agent in agents: + agent.stop.set() + for server in servers: + server.stop(grace=None) + # Drain handler and hook threads so none is still printing when the + # interpreter exits. + for client in clients: + client._stop_failure_events() + client._executor.shutdown(wait=True, cancel_futures=True) + if client._hook_executor: + client._hook_executor.shutdown(wait=True, cancel_futures=True) + if client._events_thread: + client._events_thread.join(timeout=5) + + +def reported_failure(agent): + report = agent.reports.get(timeout=5) + return report.failure if report.HasField("failure") else None + + +def test_success_reports_no_failure(run_client): + agent = HookAgent(invokes=[invoke(body="payload")]) + + def my_hooked_webhook(ctx): + return "ok" + + run_client(agent, my_hooked_webhook, Hooks()) + + assert reported_failure(agent) is None + + +def test_handler_error_is_reported_not_hooked_locally(run_client): + hooks = Hooks(action=FailureAction.RETRY) + agent = HookAgent(invokes=[invoke(body="payload")]) + + def my_hooked_webhook(ctx): + raise ValueError("ohnoes") + + run_client(agent, my_hooked_webhook, hooks) + + failure = reported_failure(agent) + assert failure.reason == FailureReason.HANDLER_ERROR + assert failure.source == FailureSource.APPLICATION + assert failure.message == "ohnoes" + # The agent sends it back as an event; the SDK doesn't run the hook itself. + with pytest.raises(queue.Empty): + hooks.failures.get(timeout=0.5) + + +def test_api_timeout_is_reported_as_runtime(run_client): + api = SlowApi() + agent = HookAgent(invokes=[invoke(timeout_ms=200)]) + + def my_hooked_webhook(ctx): + ctx.cortex_api_call("/api/v1/slow", "GET") + + try: + run_client(agent, my_hooked_webhook, Hooks(), api=api) + failure = reported_failure(agent) + finally: + api.release.set() + assert failure.reason == FailureReason.TIMEOUT + assert failure.source == FailureSource.RUNTIME + + +def test_slow_handler_is_reported_as_application_timeout(run_client): + agent = HookAgent(invokes=[invoke(timeout_ms=200)]) + finished = threading.Event() + + def my_hooked_webhook(ctx): + time.sleep(0.6) + finished.set() + + run_client(agent, my_hooked_webhook, Hooks()) + + report = agent.reports.get(timeout=5) + assert report.error.code == "timeout" + assert report.failure.reason == FailureReason.TIMEOUT + assert report.failure.source == FailureSource.APPLICATION + + # The late finish is dropped: no second report. + assert finished.wait(timeout=5) + time.sleep(0.2) + assert agent.reports.empty() + + +def test_expired_invocation_is_not_started(run_client): + """The agent has already reported an invocation past its deadline, so the + SDK must not run it: a failure hook may be replaying it.""" + ran = queue.Queue() + agent = HookAgent(invokes=[ + invoke("stale", timeout_ms=10000, deadline_in=0.5), + invoke("fresh", timeout_ms=10000, deadline_in=60), + ]) + + def my_hooked_webhook(ctx): + ran.put(ctx.args) + + run_client(agent, my_hooked_webhook, Hooks()) + + assert agent.reports.get(timeout=5).handler_invoke.invocation_id == "fresh" + time.sleep(0.5) + assert agent.reports.empty() + assert ran.qsize() == 1 + + +def test_timeout_capped_by_agent_deadline_is_runtime(run_client): + # Its own timeout is long, but the agent gives up in 1.5s: it waited. + agent = HookAgent(invokes=[invoke(timeout_ms=60000, deadline_in=1.5)]) + + def my_hooked_webhook(ctx): + time.sleep(2) + + run_client(agent, my_hooked_webhook, Hooks()) + + failure = reported_failure(agent) + assert failure.reason == FailureReason.TIMEOUT + assert failure.source == FailureSource.RUNTIME + + +def test_failure_event_runs_hook_and_answers(run_client): + hooks = Hooks(action=FailureAction.RETRY) + agent = HookAgent(events=[failure_event("lost-1", attempt=2, body="payload")]) + + run_client(agent, lambda ctx: None, hooks) + + first = agent.events_requests.get(timeout=5) + assert first.dispatch_id + assert not first.HasField("resolution") + + info, failure = hooks.failures.get(timeout=5) + assert info.invocation_id == "lost-1" + assert info.args == {"body": "payload"} + assert info.attempt == 2 + assert failure.reason == FailureReason.NO_RESOURCES + assert failure.source == FailureSource.RUNTIME + assert failure.caller_rejected + + answer = agent.resolutions.get(timeout=5) + assert answer.invocation_id == "lost-1" + assert answer.action == cortex_axon_agent_pb2.FAILURE_ACTION_RETRY + + +def test_hook_returning_nothing_drops(run_client): + agent = HookAgent(events=[failure_event("lost-1")]) + run_client(agent, lambda ctx: None, Hooks(action=None)) + + assert agent.resolutions.get(timeout=5).action == cortex_axon_agent_pb2.FAILURE_ACTION_DROP + + +def test_hook_errors_drop_and_are_contained(run_client): + agent = HookAgent(events=[failure_event("lost-1"), failure_event("lost-2")]) + + class Broken(Hooks): + def on_failure(self, info, failure): + raise RuntimeError("hook bug") + + run_client(agent, lambda ctx: None, Broken()) + + answers = [agent.resolutions.get(timeout=5) for _ in range(2)] + assert {a.invocation_id for a in answers} == {"lost-1", "lost-2"} + assert all(a.action == cortex_axon_agent_pb2.FAILURE_ACTION_DROP for a in answers) + + +def test_dispatch_request_advertises_failure_events(run_client): + with_hooks = HookAgent() + run_client(with_hooks, lambda ctx: None, Hooks()) + assert with_hooks.dispatch_requests.get(timeout=5).failure_events + + without_hooks = HookAgent() + run_client(without_hooks, lambda ctx: None) + assert not without_hooks.dispatch_requests.get(timeout=5).failure_events + assert without_hooks.events_calls == 0 + + +def test_failure_events_reach_hook_while_handlers_are_saturated(run_client): + """The agent reports lost invocations exactly when every handler slot is + busy. Those events must not wait behind the slots.""" + slots = 2 + release = threading.Event() + started = threading.Barrier(slots + 1) + events = [failure_event(f"lost-{i}", body=f"msg-{i}") for i in range(20)] + # More invocations than slots, so the dispatch reader blocks. + agent = HookAgent(invokes=[invoke(str(i)) for i in range(slots + 2)], events=events) + hooks = Hooks(action=FailureAction.RETRY) + + def my_hooked_webhook(ctx): + with contextlib.suppress(threading.BrokenBarrierError): + started.wait(timeout=5) + release.wait(timeout=10) + + try: + run_client(agent, my_hooked_webhook, hooks, max_concurrent_handlers=slots) + started.wait(timeout=5) + + seen = [hooks.failures.get(timeout=5) for _ in events] + bodies = sorted(info.args["body"] for info, _ in seen) + assert bodies == sorted(f"msg-{i}" for i in range(20)) + answered = {agent.resolutions.get(timeout=5).invocation_id for _ in events} + assert answered == {f"lost-{i}" for i in range(20)} + finally: + release.set() + started.abort() + + +def test_older_agent_without_failure_events(run_client): + ran = queue.Queue() + agent = HookAgent(invokes=[invoke()], events_code=grpc.StatusCode.UNIMPLEMENTED) + + def my_hooked_webhook(ctx): + ran.put(True) + + client = run_client(agent, my_hooked_webhook, Hooks()) + ran.get(timeout=5) + client._events_thread.join(timeout=5) + assert not client._events_thread.is_alive() + assert agent.events_calls == 1