diff --git a/app/docs/dev.md b/app/docs/dev.md index 9631f01..4d392a3 100644 --- a/app/docs/dev.md +++ b/app/docs/dev.md @@ -1,6 +1,8 @@ # ArraySymbolicEqual -This evaluation function can take any level of nesting for "response" and "answer" fields, as comparison is done recursively (as long as both shapes are identical). Symbolic grading is done using the [SymbolicEqual](https://lambda-feedback.github.io/user-documentation/user_eval_function_docs/symbolicEqual/) function, called using the experimental EvaluationFunctionClient from the evaluation-function-utils library. +This evaluation function can take any level of nesting for "response" and "answer" fields, as comparison is done recursively (as long as both shapes are identical). Symbolic grading is done using the [SymbolicEqual](https://lambda-feedback.github.io/user-documentation/user_eval_function_docs/symbolicEqual/) function, called over HTTPS. + +The full URL of the `symbolicEqual` function to call is read from the `SYMBOLIC_EQUAL_URL` environment variable (e.g. `https://.execute-api.eu-west-2.amazonaws.com/default/symbolicEqual`), which must be set on the deployed function. No AWS credentials or IAM permissions are needed. ## Inputs This compares cells using the `symbolicEqual` function. Please consult that function's documentation for details on it's allowable parameters, as the ones provided to this function are fed through as they are. diff --git a/app/evaluation.py b/app/evaluation.py index 551b8b2..2d73728 100644 --- a/app/evaluation.py +++ b/app/evaluation.py @@ -1,6 +1,8 @@ -import re +import json +import os +import urllib.error +import urllib.request -from evaluation_function_utils.client import EvaluationFunctionClient from evaluation_function_utils.errors import EvaluationException try: @@ -8,7 +10,62 @@ except ImportError: from shape import shape_feedback -client = EvaluationFunctionClient(env_path=".env") +# Full URL of the symbolicEqual function to call, e.g. +# https://.execute-api.eu-west-2.amazonaws.com/default/symbolicEqual +SYMBOLIC_EQUAL_URL_ENV = "SYMBOLIC_EQUAL_URL" + +# API Gateway HTTP APIs time out after 30 seconds. +REQUEST_TIMEOUT_SECONDS = 30 + + +class EvaluationFunctionInvoker: + """ + Calls another deployed evaluation function over HTTPS, the same way any + other client does. No AWS credentials or IAM permissions are needed. + """ + + def invoke(self, url, response, answer, params=None): + data = json.dumps({ + "response": response, + "answer": answer, + "params": params or {}, + }).encode("utf-8") + request = urllib.request.Request( + url, + data=data, + method="POST", + headers={"Content-Type": "application/json", "command": "eval"}, + ) + + try: + with urllib.request.urlopen( + request, timeout=REQUEST_TIMEOUT_SECONDS) as res: + decoded_str = res.read().decode("utf-8") + except urllib.error.HTTPError as e: + raise RuntimeError(f"{url} returned HTTP {e.code}") from e + except urllib.error.URLError as e: + raise RuntimeError(f"Request to {url} failed: {e.reason}") from e + + try: + decoded = json.loads(decoded_str) + except ValueError: + raise EvaluationException( + f"Response from {url} could not be parsed.", + raw_response=decoded_str) + + # Re-raise evaluation errors as if the function was run locally. + if "error" in decoded: + raise EvaluationException(**decoded["error"]) + + if "result" in decoded: + return decoded["result"] + + raise EvaluationException( + f"{url} did not return an error or a result.", + raw_response=decoded) + + +client = EvaluationFunctionInvoker() def grade_single_cell(res, ans, params): @@ -16,8 +73,12 @@ def grade_single_cell(res, ans, params): Attempt to grade a single cell using the SymbolicEqual function, fallback to a local version if the request fails """ + url = os.getenv(SYMBOLIC_EQUAL_URL_ENV) + if not url: + raise RuntimeError(f"{SYMBOLIC_EQUAL_URL_ENV} is not set") + try: - return client.invoke('symbolicEqual', res, ans, params=params) + return client.invoke(url, res, ans, params=params) except EvaluationException as e: return e.error_dict diff --git a/app/evaluation_tests.py b/app/evaluation_tests.py index eab13ae..c060709 100644 --- a/app/evaluation_tests.py +++ b/app/evaluation_tests.py @@ -1,26 +1,64 @@ +import io +import json +import os import unittest from unittest import mock -from evaluation_function_utils.client import MissingCredentials +try: + from . import evaluation +except ImportError: + import evaluation +evaluation_function = evaluation.evaluation_function -def import_evaluation(): - try: - from . import evaluation - except ImportError: - import evaluation - return evaluation +URL = "https://gateway.example.com/default/symbolicEqual" -# The real client needs AWS credentials on creation. Without them, import -# with a mock client so the tests below (which mock the client) can still run. -try: - evaluation = import_evaluation() -except MissingCredentials: - with mock.patch("evaluation_function_utils.client.EvaluationFunctionClient"): - evaluation = import_evaluation() -evaluation_function = evaluation.evaluation_function +class TestEvaluationFunctionInvoker(unittest.TestCase): + """Tests for calling another function over HTTPS.""" + + def call(self, body): + """Invoke with a mocked HTTP response; returns (result, request).""" + res = mock.MagicMock() + res.read.return_value = json.dumps(body).encode("utf-8") + res.__enter__.return_value = res + + with mock.patch.object(evaluation.urllib.request, "urlopen", + return_value=res) as urlopen: + result = evaluation.EvaluationFunctionInvoker().invoke( + URL, "a", "a", params={"x": 1}) + return result, urlopen.call_args.args[0] + + def test_returns_result(self): + result, request = self.call( + {"command": "eval", "result": {"is_correct": True}}) + + self.assertEqual(result, {"is_correct": True}) + self.assertEqual(request.full_url, URL) + self.assertEqual(request.get_method(), "POST") + self.assertEqual(request.get_header("Command"), "eval") + self.assertEqual(json.loads(request.data), { + "response": "a", "answer": "a", "params": {"x": 1}, + }) + + def test_error_raises_evaluation_exception(self): + with self.assertRaises(evaluation.EvaluationException) as ctx: + self.call({"error": {"message": "parse failed"}}) + self.assertEqual(ctx.exception.message, "parse failed") + + def test_http_error_raises(self): + error = evaluation.urllib.error.HTTPError( + URL, 500, "Internal Server Error", {}, io.BytesIO(b"")) + with mock.patch.object(evaluation.urllib.request, "urlopen", + side_effect=error): + with self.assertRaises(RuntimeError): + evaluation.EvaluationFunctionInvoker().invoke(URL, "a", "a") + + def test_missing_url_raises(self): + with mock.patch.dict(os.environ, {}, clear=True): + with self.assertRaises(RuntimeError): + evaluation.grade_single_cell("a", "a", {}) class TestEvaluationFunction(unittest.TestCase): @@ -47,6 +85,11 @@ def setUp(self): self.client = patcher.start() self.addCleanup(patcher.stop) + env = mock.patch.dict(os.environ, + {evaluation.SYMBOLIC_EQUAL_URL_ENV: URL}) + env.start() + self.addCleanup(env.stop) + def assert_size_feedback(self, response, answer, feedback): result = evaluation_function(response, answer, {}) @@ -111,8 +154,8 @@ def test_answer_not_list(self): evaluation_function(["a"], "a", {}) """ - NOTE: This function was converted to use the experimental - EvaluationFunctionClient which doesn't support testing yet. + NOTE: These tests call the deployed symbolicEqual function, so they + can't run in CI without AWS access. def test_vector_incorrect(self): response = ["a + b - a", "2 + c", "d"] diff --git a/app/requirements.txt b/app/requirements.txt index 7664e06..286a6f5 100755 --- a/app/requirements.txt +++ b/app/requirements.txt @@ -1,2 +1,2 @@ numpy -evaluation-function-utils \ No newline at end of file +evaluation-function-utils