diff --git a/README.md b/README.md index 8b015ec..97d5b63 100644 --- a/README.md +++ b/README.md @@ -318,8 +318,12 @@ runs as edited. What a generated entrypoint cannot carry is in the list above: a module whose manifest says which files it is, or names a runtime, keeps that runtime -instead. There is no `debug` terminal on this path, and a function error -reaches the caller as the exec failure with the process's stderr. +instead. There is no `debug` terminal on this path. A function error reaches +the caller as its own error. On an engine that gives the call's process +`DAGGER_FUNCTION_ERROR_PATH`, it keeps its values, such as an exec's exit code +and output, so a caller sees an `ExecError`; on an older engine, only its +message gets past the entrypoint. Either way, an API error keeps the call it +names as its origin. Generation writes an entrypoint into a module that has none, or whose manifest names one served from elsewhere, and leaves a Dang entrypoint in the module's diff --git a/sdk/src/dagger/mod/__main__.py b/sdk/src/dagger/mod/__main__.py index 8cc2204..9f546c5 100644 --- a/sdk/src/dagger/mod/__main__.py +++ b/sdk/src/dagger/mod/__main__.py @@ -15,7 +15,14 @@ from dagger import telemetry from dagger._exceptions import QueryError from dagger.client._session import mark_module_runtime -from dagger.mod._exceptions import ModuleError +from dagger.mod._exceptions import ( + FUNCTION_ERROR_PATH_ENV, + ErrorOriginFilter, + ModuleError, + function_error_message, + report_function_error, + write_function_error, +) logger = logging.getLogger(__package__) @@ -62,17 +69,42 @@ def main(argv: list[str] | None = None) -> int: call.set_defaults(run=_call) args = parser.parse_args(argv) + if _error_file(args): + # The engine reads an error's origin from the file. + logger.addFilter(ErrorOriginFilter()) try: args.run(args) except (ModuleError, QueryError) as e: - logger.error(str(e)) # noqa: TRY400 - the message is the whole story + # The engine shows an error it is given in a file; logging it + # would show it twice. + if not _error_file(args): + logger.error(str(e)) # noqa: TRY400 - the message is the whole story + _report(args, e) return 2 - except Exception: + except Exception as e: logger.exception("Unhandled exception") + _report(args, e) return 1 return 0 +def _error_file(args: argparse.Namespace) -> str: + """The file the engine gives a call's process for its error, if any.""" + if args.run is not _call: + return "" + return os.environ.get(FUNCTION_ERROR_PATH_ENV, "") + + +def _report(args: argparse.Namespace, exc: Exception) -> None: + """Give the engine a failed call's error, after everything it logged.""" + if args.run is not _call: + return + if path := _error_file(args): + write_function_error(path, exc) + else: + report_function_error(function_error_message(exc)) + + def _entrypoint(args: argparse.Namespace) -> None: from dagger.client._descriptor import registering_types from dagger.mod._entrypoint import write_entrypoint @@ -104,17 +136,22 @@ def _call(args: argparse.Namespace) -> None: request = json.load(sys.stdin) telemetry.initialize() try: - result = anyio.run(_dispatch, request) + result = anyio.run(_dispatch, request, bool(_error_file(args))) finally: telemetry.shutdown() args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result)) -async def _dispatch(request: dict[str, Any]) -> Any: +async def _dispatch(request: dict[str, Any], error_file: bool) -> Any: from dagger.mod.cli import load_module - return await load_module().dispatch(request) + # The file keeps the error's whole traceback: the logs show the user's + # code, and nothing of an API error the engine shows the origin of, the + # call that failed with its logs. + mod = load_module(short_tracebacks=error_file) + mod.short_tracebacks = error_file + return await mod.dispatch(request) def _exit(code: int) -> None: diff --git a/sdk/src/dagger/mod/_entrypoint.py b/sdk/src/dagger/mod/_entrypoint.py index 2060bff..50e6c35 100644 --- a/sdk/src/dagger/mod/_entrypoint.py +++ b/sdk/src/dagger/mod/_entrypoint.py @@ -14,6 +14,7 @@ ObjectDescription, TypeRef, ) +from dagger.mod._exceptions import FUNCTION_ERROR_MARKER HEADER = "# Code generated by dagger. DO NOT EDIT.\n" @@ -63,6 +64,7 @@ def render_main(name: str, client_version: str, outside: Sequence[str] = ()) -> for path in outside ), exclude=SOURCES_EXCLUDE, + marker=_quote(FUNCTION_ERROR_MARKER), ) @@ -203,6 +205,13 @@ def _indent(lines: list[str], width: int) -> list[str]: SOURCES_EXCLUDE = '["**/.git", "**/.venv", "**/__pycache__"]' +# A call's process has no current function call to return an error to, so a +# failed call fails its exec, whose error carries the end of the process's +# stderr. call() raises the error that the last marker line there reports +# (report_function_error), and the exec's own error when there is none: the +# exec failed before the function did. The exec still fails, so a failed call +# is not cached. The build is synced first so that its failure stays out of +# the rescue and keeps its values, such as the failed install's output. MAIN_TEMPLATE = """{header} # Needs Dagger v1.0.0-beta.26 or later; older engines report a missing "naming" field. type Entrypoint implements ModuleEntrypoint {{ @@ -231,15 +240,29 @@ def _indent(lines: list[str], width: int) -> list[str]: fnName: fnName, fnArgs: fnArgs, }}}}) - let result = runtime + let installed = runtime .withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "") .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + .sync + let result = installed .withExec(["python", "-m", "dagger.mod", "call", "--output", "/dagger/result.json"], stdin: request, experimentalPrivilegedNesting: true) .file("/dagger/result.json") - .contents + .contents rescue {{ + err: GraphQLError => raiseFunctionError(err) + }} (result :: JSON!) }} + let raiseFunctionError(err: GraphQLError!): String! {{ + let marker = {marker} + let stderr = ((JSON.decode(err.extensions) :: {{{{stderr: String}}}}).stderr ?? "") rescue "" + let lines = stderr.split("\\n").filter {{ line => line.hasPrefix(marker) }} + if (lines.isEmpty) {{ + raise err + }} + raise ((JSON.decode(lines.takeLast(1).join("").trimPrefix(marker)) :: String!) rescue err.message) + }} + let runtime: Container! {{ PythonModuleBuild( contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), diff --git a/sdk/src/dagger/mod/_exceptions.py b/sdk/src/dagger/mod/_exceptions.py index e1a0371..5f5446d 100644 --- a/sdk/src/dagger/mod/_exceptions.py +++ b/sdk/src/dagger/mod/_exceptions.py @@ -1,8 +1,18 @@ +import functools +import importlib.metadata import json +import linecache import logging +import os +import pathlib +import re +import site +import sys +import sysconfig import traceback -from collections.abc import Mapping -from typing import Any +from collections.abc import Iterable, Mapping +from types import FrameType +from typing import Any, Final import cattrs from opentelemetry.semconv.attributes.exception_attributes import ( @@ -125,6 +135,331 @@ def log_exception_only( logger.error(msg, *args, exc_info=(type(exc), exc, None)) +FUNCTION_ERROR_MARKER: Final = "::dagger-function-error::" +"""Starts the line on which a call reports the function's error. + +The generated entrypoint raises the text after it as the function's error. +""" + +# A failed exec gives the entrypoint only the last 100 KiB of its stderr. JSON +# escapes a character in at most six bytes, so 16 Ki characters fit. +_REPORTED_ERROR_LIMIT: Final = 16 << 10 + +# The engine finds where an error comes from by these, at the message's end. +_ERROR_ORIGIN: Final = re.compile(r"\s*\[traceparent:[0-9a-f]{32}-[0-9a-f]{16}\]") + + +def function_error_message(exc: BaseException, *, logged: bool = False) -> str: + """The error a failed call reports: the function's own, not its wrapper. + + An API error's message is kept whole, with the origin it names. Each + error of a group is reported, as a task group raises them. An exception + the function raised is named with its type, unless `logged` says its + traceback, which names it, is already in the function's logs. + """ + if isinstance(exc, FunctionError) and exc.__cause__ is not None: + if logged and not isinstance(exc.__cause__, BaseExceptionGroup): + return str(exc) or type(exc.__cause__).__name__ + exc = exc.__cause__ + if isinstance(exc, BaseExceptionGroup): + return "; ".join(function_error_message(e) for e in exc.exceptions) + if isinstance(exc, ModuleError | QueryError): + return str(exc) or type(exc).__name__ + return f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__ + + +FUNCTION_ERROR_PATH_ENV: Final = "DAGGER_FUNCTION_ERROR_PATH" +"""The file the engine gives a call's process to write the function's error to. + +An engine that sets it fails the call with the error written there; one that +doesn't reads the FUNCTION_ERROR_MARKER line instead. +""" + + +class ErrorOriginFilter(logging.Filter): + """Leave the error origins out of what a call's process logs. + + An API error's message ends with the origin the engine finds it by, such + as `[traceparent:...]`: plumbing for the engine, which reads it from the + error the process reports, and noise in the function's logs, a traceback + included. + """ + + def filter(self, record: logging.LogRecord) -> bool: + if record.exc_info and not record.exc_text: + record.exc_text = logging.Formatter().formatException(record.exc_info) + if record.exc_text: + record.exc_text = _ERROR_ORIGIN.sub("", record.exc_text) + message = record.getMessage() + if _ERROR_ORIGIN.search(message): + record.msg, record.args = _ERROR_ORIGIN.sub("", message), None + return True + + +def has_error_origin(exc: QueryError) -> bool: + """Whether an API error names the origin the engine shows it at. + + The engine shows such an error where it comes from, the call that failed + with its logs. One that names none, such as an ID that fails to load, is + only shown by the function that got it. + """ + return any(_ERROR_ORIGIN.search(error.message) for error in exc.errors) + + +def errors_to_show(exc: BaseException) -> BaseException | None: + """What of a function's error its logs show, if anything. + + Not an API error that `has_error_origin`: the engine shows it where it + comes from. Each error of a group is judged, as a task group raises them. + """ + if isinstance(exc, QueryError): + return None if has_error_origin(exc) else exc + if isinstance(exc, BaseExceptionGroup): + shown_elsewhere, rest = exc.split( + lambda e: isinstance(e, QueryError) and has_error_origin(e) + ) + # The group itself, of the user's own type, when it loses nothing. + return exc if shown_elsewhere is None else rest + return exc + + +def print_user_traceback(exc: BaseException) -> None: + """Show an exception as Python shows an uncaught one, in the user's code. + + For a call that reports its error in the engine's file, which keeps the + whole traceback: the function's logs show just where the user's code + failed. See `format_user_traceback`. + """ + sys.stderr.write(format_user_traceback(exc)) + sys.stderr.flush() + + +def format_user_traceback(exc: BaseException) -> str: + """Format an exception's traceback with the user's frames only. + + The frames of the module's own source files are kept. Those of the SDK, + of the code dagger generates (the module's clients), of the standard + library and of the packages not installed from a local directory (from + an index, say) are left out, in each exception it chains too, and so are + the error origins, as `ErrorOriginFilter` leaves them out of logs. An + exception without a frame of the user's is shown without a traceback, as + its type and message. + """ + te = traceback.TracebackException.from_exception(exc, compact=True) + _keep_user_frames(te, exc, set()) + return _ERROR_ORIGIN.sub("", "".join(te.format())) + + +def _keep_user_frames( + te: traceback.TracebackException, + exc: BaseException, + seen: set[int], +) -> None: + if id(exc) in seen: + return + seen.add(id(exc)) + user_files = { + frame.f_code.co_filename + for frame, _ in traceback.walk_tb(exc.__traceback__) + if _is_user_frame(frame) + } + te.stack = traceback.StackSummary.from_list( + [frame for frame in te.stack if frame.filename in user_files] + ) + for chained_te, chained in ( + (te.__cause__, exc.__cause__), + (te.__context__, exc.__context__), + ): + if chained_te is not None and chained is not None: + _keep_user_frames(chained_te, chained, seen) + if te.exceptions and isinstance(exc, BaseExceptionGroup): + for group_te, grouped in zip(te.exceptions, exc.exceptions, strict=False): + _keep_user_frames(group_te, grouped, seen) + + +_GENERATED_HEADER: Final = "# Code generated by dagger." +"""Starts the files dagger generates, such as the clients of a module.""" + + +def _is_user_frame(frame: FrameType) -> bool: + """Whether a frame runs the module's own code.""" + # The spec names the module run as `__main__` too (`python -m dagger.mod`). + spec = frame.f_globals.get("__spec__") + module = getattr(spec, "name", None) or frame.f_globals.get("__name__") or "" + if module.partition(".")[0] == __name__.partition(".")[0]: + return False + filename = frame.f_code.co_filename + # Frozen and compiled code, such as importlib's. + if not filename or filename.startswith("<"): + return False + if linecache.getline(filename, 1).startswith(_GENERATED_HEADER): + return False + path = os.path.realpath(filename) + if path.startswith(_installed_paths()): + # The runtime installs the members of the module's workspace, its + # own libraries among them, from their directories, not editable. + return path in _local_files() + return not path.startswith(_dirs("stdlib", "platstdlib")) + + +def _installed_paths() -> tuple[str, ...]: + """The directories of the installed packages.""" + return _dirs("purelib", "platlib") + _site_dirs() + + +@functools.cache +def _dirs(*names: str) -> tuple[str, ...]: + return _as_dirs(sysconfig.get_path(name) for name in names) + + +@functools.cache +def _site_dirs() -> tuple[str, ...]: + return _as_dirs([*site.getsitepackages(), site.getusersitepackages()]) + + +def _as_dirs(paths: Iterable[str]) -> tuple[str, ...]: + return tuple(os.path.realpath(path) + os.sep for path in paths if path) + + +@functools.cache +def _local_files() -> frozenset[str]: + """The files of the distributions installed from a local directory. + + Files, not packages: the distributions of a namespace package share it. + """ + return frozenset( + os.path.realpath(str(dist.locate_file(file))) + for dist in importlib.metadata.distributions() + if _installed_from_directory(dist) + for file in dist.files or () + ) + + +def _installed_from_directory(dist: importlib.metadata.Distribution) -> bool: + """Whether a distribution was installed from a local directory (PEP 610).""" + try: + info = json.loads(dist.read_text("direct_url.json") or "{}") + except ValueError: + return False + return ( + isinstance(info, dict) + and str(info.get("url", "")).startswith("file:") + and "dir_info" in info + ) + + +def _limit(message: str) -> str: + if len(message) > _REPORTED_ERROR_LIMIT: + origins = "".join(_ERROR_ORIGIN.findall(message[_REPORTED_ERROR_LIMIT:])) + message = message[:_REPORTED_ERROR_LIMIT] + "..." + origins + return message + + +def write_function_error(path: str, exc: BaseException) -> None: + """Give the engine a failed call's error in the file it names. + + The engine fails the call with this error as the function's own, as with + `record_exception`: `{"message": ..., "values": {...}}`, the message in + full and the values `function_error_values` gives. An API error's + message names the call that failed, so that call stays the error's + origin; any other error comes from the function call. + """ + # The traceback, which names the exception's type, is already in the + # function's logs. + message = function_error_message(exc, logged=True) + if isinstance(exc, FunctionError) and exc.__cause__ is not None: + # The values of the error the FunctionError wraps, and the extra + # values it adds. + values = {**function_error_values(exc.__cause__), **_extra_values(exc)} + else: + values = function_error_values(exc) + values = {key: _json_value(value) for key, value in values.items()} + encoded = _function_error_report(message, values) + if len(encoded.encode()) > _FUNCTION_ERROR_LIMIT: + # The engine reads none of a report over its limit: keep the + # message, and the values that fit. + message = _limit(message) + values = { + key: _limit(value) if isinstance(value, str) else value + for key, value in values.items() + if key != EXCEPTION_STACKTRACE + } + encoded = _function_error_report(message, values) + if len(encoded.encode()) > _FUNCTION_ERROR_LIMIT: + encoded = _function_error_report(message, {}) + pathlib.Path(path).write_text(encoded, encoding="utf-8") + + +_FUNCTION_ERROR_LIMIT: Final = 1 << 20 +"""The largest error file the engine reads, in bytes.""" + + +def _function_error_report(message: str, values: dict[str, Any]) -> str: + return json.dumps({"message": message, "values": values}, ensure_ascii=False) + + +def function_error_values(exc: BaseException) -> dict[str, Any]: + """The values of the error a failed call reports for `exc`. + + Those `record_exception` gives its `dagger.Error`: the exception's type, + message and stack trace, a ModuleError's `extra` values, and an API + error's extensions, such as an ExecError's exit code and output, whole. + Unlike `record_exception`, the API error may also be one the exception + was raised from (`raise ... from`), as one that adds to its message is, + whose values the exception's own come before; an exception raised while + handling one is its own error. + """ + attrs: dict[str, Any] = {**_extra_values(exc), **_exception_attributes(exc)} + if isinstance(exc, QueryError): + attrs.update(exc.error.extensions) + elif (api_error := _raised_from_query_error(exc)) is not None: + attrs = {**api_error.error.extensions, **attrs} + return attrs + + +def _extra_values(exc: BaseException) -> dict[str, Any]: + """A ModuleError's `extra` values, as the error's values.""" + if isinstance(exc, ModuleError) and exc.extra: + return {f"extra.{key}": val for key, val in exc.extra.items()} + return {} + + +def _raised_from_query_error(exc: BaseException) -> QueryError | None: + """The API error exc was raised from, directly or not, if any.""" + seen: set[int] = set() + cur = exc.__cause__ + while cur is not None and id(cur) not in seen: + if isinstance(cur, QueryError): + return cur + seen.add(id(cur)) + cur = cur.__cause__ + return None + + +def _json_value(value: Any) -> Any: + """The value if it is JSON, else its repr, as `_safe_json_dumps` does.""" + try: + json.dumps(value) + except (TypeError, ValueError): + return repr(value) + return value + + +def report_function_error(message: str) -> None: + """Report a failed call's error as the last line of stderr. + + The process that runs a call has no current function call to return its + error to, so its exec fails, and the generated entrypoint raises the + message from this line instead of the exec's exit code. An API error's + message names the call that failed, so that call becomes the error's + origin, not the process. An engine that gives the process a file for the + error (FUNCTION_ERROR_PATH_ENV) gets it there instead. + """ + encoded = json.dumps(_limit(message), ensure_ascii=False) + sys.stderr.write(f"\n{FUNCTION_ERROR_MARKER}{encoded}\n") + sys.stderr.flush() + + async def record_exception(exc: Exception): """Convert a Python exception into a `dagger.Error`.""" attrs: dict[str, Any] = _exception_attributes(exc) @@ -162,7 +497,7 @@ async def record_exception(exc: Exception): span.record_exception(exc) -def _exception_attributes(exc: Exception) -> dict[str, str]: +def _exception_attributes(exc: BaseException) -> dict[str, str]: message = str(exc) stacktrace = "".join(traceback.format_exception(exc)) module = type(exc).__module__ diff --git a/sdk/src/dagger/mod/_module.py b/sdk/src/dagger/mod/_module.py index a5c4968..6da7f0a 100644 --- a/sdk/src/dagger/mod/_module.py +++ b/sdk/src/dagger/mod/_module.py @@ -38,7 +38,10 @@ ModuleError, ObjectNotFoundError, RegistrationError, + errors_to_show, + has_error_origin, log_exception_only, + print_user_traceback, transform_error, ) from dagger.mod._naming import ModuleNames, module_names @@ -99,6 +102,12 @@ def __init__(self, main_name: str = MAIN_OBJECT): # from exceptions raised in functions by default. Not documented # intentionally for now. self.log_exceptions = True + # Whether a function's errors are shown with a short traceback, through + # the user's code only. A call that reports its error in the file the + # engine gives it turns this on, the file keeping the whole traceback. + # An API error is then not shown at all when the engine shows its + # origin, the call that failed with its logs. + self.short_tracebacks = False @property def main_cls(self) -> type[ObjectType]: @@ -298,13 +307,31 @@ async def dispatch(self, request: Mapping[str, Any]) -> Any: except ValueError as e: msg = "Unable to decode the call request" raise InvalidInputError(msg, extra={"request": request}) from e - await self.load_names() - return await self.get_result( - request["receiverType"], - parent_state or {}, - request["fnName"], - inputs, - ) + try: + await self.load_names() + return await self.get_result( + request["receiverType"], + parent_state or {}, + request["fnName"], + inputs, + ) + except QueryError as e: + # The engine shows where an API error comes from, the call that + # failed with its logs, unless it names no origin, such as an ID + # that fails to load: then show where the function got it, + # whether in its own code or loading its arguments or result. + if self.short_tracebacks and not has_error_origin(e): + print_user_traceback(e) + raise + + def _raises_api_error(self, e: Exception) -> bool: + """Whether an API error goes on as it is rather than wrapped. + + A call that reports its error in the engine's file fails with the + API error itself, which names where it comes from, as `dispatch` + shows it, rather than as an invalid input or result. + """ + return self.short_tracebacks and isinstance(e, QueryError) async def get_result( self, @@ -324,6 +351,9 @@ async def get_result( try: return await self.unstructure(result, fn.return_type) except Exception as e: + if self._raises_api_error(e): + # Such as the ID of a returned object that fails to load. + raise log_exception_only(e, "Invalid result from function") msg = transform_error( e, @@ -403,27 +433,43 @@ async def call(self, func: Func[P, R], *args: P.args, **kwargs: P.kwargs) -> R: # Escape hatch to fully control logging from user code. raise except QueryError as e: - tb = e.__traceback__ - # Exclude the line in "try" above - if tb: - tb = tb.tb_next # Exclude the underlying TransportQueryError to reduce noise e.__cause__ = None - logger.exception( - "API error while executing function", - exc_info=(type(e), e, tb), - ) + self._show_api_error(e) # Preserve API error so it's properly propagated. raise e from None except Exception as e: # Escape hatch if too noisy. if self.log_exceptions: - # Logging the exception will show the full stack trace on stderr. - logger.exception("Unhandled exception while executing function") + self._show_exception(e) raise FunctionError(str(e)) from e return result + def _show_api_error(self, e: QueryError) -> None: + """Show an API error a function raised in the function's logs.""" + if self.short_tracebacks: + # `dispatch` shows it, as any API error the call fails with. + return + tb = e.__traceback__ + # Exclude the line in "try" in `call` + if tb: + tb = tb.tb_next + logger.exception( + "API error while executing function", + exc_info=(type(e), e, tb), + ) + + def _show_exception(self, e: Exception) -> None: + """Show an exception a function raised in the function's logs.""" + if self.short_tracebacks: + # A task group raises API errors in a group. + if (shown := errors_to_show(e)) is not None: + print_user_traceback(shown) + return + # Logging the exception will show the full stack trace on stderr. + logger.exception("Unhandled exception while executing function") + async def structure(self, obj: Any, cl: type[T]) -> T: """Convert a primitive value to the expected type.""" return await asyncify(self._converter.structure, obj, cl) @@ -452,6 +498,8 @@ async def _get_parent_instance( try: return await self.structure(state, obj_type.cls) except Exception as e: + if self._raises_api_error(e): + raise log_exception_only(e, "Failed to instantiate parent object") msg = transform_error( e, @@ -496,6 +544,8 @@ async def _convert_inputs( try: kwargs[python_name] = await self.structure(value, type_) except Exception as e: + if self._raises_api_error(e): + raise log_exception_only( e, "Failed to convert from primitive input value for argument '%s'", diff --git a/sdk/src/dagger/mod/cli.py b/sdk/src/dagger/mod/cli.py index 2dfe951..01d0361 100644 --- a/sdk/src/dagger/mod/cli.py +++ b/sdk/src/dagger/mod/cli.py @@ -16,7 +16,12 @@ from dagger.client._connection import connect from dagger.client._descriptor import registering_types from dagger.client._session import mark_module_runtime -from dagger.mod._exceptions import ModuleError, ModuleLoadError, record_exception +from dagger.mod._exceptions import ( + ModuleError, + ModuleLoadError, + print_user_traceback, + record_exception, +) from dagger.mod._module import MAIN_OBJECT, Module logger = logging.getLogger(__package__) @@ -60,16 +65,24 @@ async def main(mod: Module | None = None, register: bool = False) -> int | None: return 1 -def load_module() -> Module: - """Load the dagger.Module instance via the main object entry point.""" +def load_module(*, short_tracebacks: bool = False) -> Module: + """Load the dagger.Module instance via the main object entry point. + + With `short_tracebacks`, an error importing the user's code is shown + with a traceback through that code only, as `Module.short_tracebacks` + shows a function's. + """ ep = get_entry_point() try: cls = ep.load() except Exception as e: - logger.exception( - "Error while importing Python module '%s' with Dagger functions", - ep.module, - ) + if short_tracebacks: + print_user_traceback(e) + else: + logger.exception( + "Error while importing Python module '%s' with Dagger functions", + ep.module, + ) raise ModuleLoadError(str(e)) from e _resume_gc() try: diff --git a/sdk/tests/mod/golden/main.dang b/sdk/tests/mod/golden/main.dang index 5d3c33b..a001897 100644 --- a/sdk/tests/mod/golden/main.dang +++ b/sdk/tests/mod/golden/main.dang @@ -27,15 +27,29 @@ type Entrypoint implements ModuleEntrypoint { fnName: fnName, fnArgs: fnArgs, }}) - let result = runtime + let installed = runtime .withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "") .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + .sync + let result = installed .withExec(["python", "-m", "dagger.mod", "call", "--output", "/dagger/result.json"], stdin: request, experimentalPrivilegedNesting: true) .file("/dagger/result.json") - .contents + .contents rescue { + err: GraphQLError => raiseFunctionError(err) + } (result :: JSON!) } + let raiseFunctionError(err: GraphQLError!): String! { + let marker = "::dagger-function-error::" + let stderr = ((JSON.decode(err.extensions) :: {{stderr: String}}).stderr ?? "") rescue "" + let lines = stderr.split("\n").filter { line => line.hasPrefix(marker) } + if (lines.isEmpty) { + raise err + } + raise ((JSON.decode(lines.takeLast(1).join("").trimPrefix(marker)) :: String!) rescue err.message) + } + let runtime: Container! { PythonModuleBuild( contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), diff --git a/sdk/tests/mod/golden/main_outside.dang b/sdk/tests/mod/golden/main_outside.dang index 230304a..7effdfa 100644 --- a/sdk/tests/mod/golden/main_outside.dang +++ b/sdk/tests/mod/golden/main_outside.dang @@ -29,15 +29,29 @@ type Entrypoint implements ModuleEntrypoint { fnName: fnName, fnArgs: fnArgs, }}) - let result = runtime + let installed = runtime .withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "") .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + .sync + let result = installed .withExec(["python", "-m", "dagger.mod", "call", "--output", "/dagger/result.json"], stdin: request, experimentalPrivilegedNesting: true) .file("/dagger/result.json") - .contents + .contents rescue { + err: GraphQLError => raiseFunctionError(err) + } (result :: JSON!) } + let raiseFunctionError(err: GraphQLError!): String! { + let marker = "::dagger-function-error::" + let stderr = ((JSON.decode(err.extensions) :: {{stderr: String}}).stderr ?? "") rescue "" + let lines = stderr.split("\n").filter { line => line.hasPrefix(marker) } + if (lines.isEmpty) { + raise err + } + raise ((JSON.decode(lines.takeLast(1).join("").trimPrefix(marker)) :: String!) rescue err.message) + } + let runtime: Container! { PythonModuleBuild( contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]), diff --git a/sdk/tests/mod/test_dispatch.py b/sdk/tests/mod/test_dispatch.py index 8ea5f0a..e0d4cb6 100644 --- a/sdk/tests/mod/test_dispatch.py +++ b/sdk/tests/mod/test_dispatch.py @@ -1,15 +1,34 @@ +import importlib import json +import logging +import os import pathlib import subprocess import sys import pytest -from dagger.mod import Module -from dagger.mod._exceptions import InvalidInputError +from dagger import QueryError +from dagger._exceptions import QueryErrorValue +from dagger.mod import Module, _exceptions +from dagger.mod._exceptions import ( + FUNCTION_ERROR_MARKER, + FUNCTION_ERROR_PATH_ENV, + ErrorOriginFilter, + FunctionError, + InvalidInputError, + errors_to_show, + format_user_traceback, + function_error_message, + has_error_origin, + report_function_error, + write_function_error, +) pytestmark = pytest.mark.anyio +ORIGIN = " [traceparent:" + "a" * 32 + "-" + "b" * 16 + "]" + @pytest.fixture def mod() -> Module: @@ -66,6 +85,31 @@ async def test_null_argument(mod: Module): assert await mod.dispatch(request) == "foo" +@pytest.mark.parametrize(("origin", "shown"), [("", True), (ORIGIN, False)]) +async def test_dispatch_shows_an_api_error_before_the_call( + mod: Module, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + origin: str, + shown: bool, +): + async def load_names(): + raise _query_error("no such module" + origin) + + monkeypatch.setattr(mod, "load_names", load_names) + mod.short_tracebacks = True + request = { + "receiverType": "Foo", + "receiverValue": "{}", + "fnName": "hello", + "fnArgs": "{}", + } + with pytest.raises(QueryError): + await mod.dispatch(request) + err = capsys.readouterr().err + assert ("QueryError: no such module\n" in err) is shown, err + + async def test_malformed_request(mod: Module): request = { "receiverType": "Foo", @@ -83,7 +127,9 @@ def module_dir(tmp_path: pathlib.Path) -> pathlib.Path: pkg = tmp_path / "src" / "hello" pkg.mkdir(parents=True) (pkg / "__init__.py").write_text( - "from dagger import function, object_type\n\n" + "from dagger import function, object_type\n" + "from dagger.client import gen\n" + "from dagger.client._core import Context\n\n" "@object_type\nclass Hello:\n" " @function\n" " def hi(self, who: str) -> str:\n" @@ -91,11 +137,65 @@ def module_dir(tmp_path: pathlib.Path) -> pathlib.Path: " @function\n" " def boom(self) -> str:\n" " raise RuntimeError('boom')\n" + " @function\n" + " def api_boom(self, origin: str = '') -> str:\n" + " from dagger import QueryError\n" + " from dagger._exceptions import QueryErrorValue\n" + " ext = {'_type': 'EXEC_ERROR', 'cmd': ['false'], 'exitCode': 1,\n" + " 'stdout': 'out', 'stderr': 'err'}\n" + " err = QueryErrorValue('exit code: 1' + origin, extensions=ext)\n" + " raise QueryError([err], 'query')\n" + " @function\n" + " def group_boom(self, origin: str = '') -> str:\n" + " from dagger import QueryError\n" + " from dagger._exceptions import QueryErrorValue\n" + " err = QueryError([QueryErrorValue('exit code: 1' + origin)], 'q')\n" + " raise ExceptionGroup('unhandled errors in a TaskGroup', [err])\n" + " @function\n" + " def unloadable(self, origin: str = '') -> gen.Container:\n" + " return _Unloadable(Context(), origin)\n" + " @function\n" + " def sdk_boom(self) -> str:\n" + " return _sdk_boom()\n" + " @function\n" + " def wrapped_boom(self) -> str:\n" + " try:\n" + " _sdk_boom()\n" + " except ValueError as e:\n" + " raise RuntimeError(f'wrapped: {e}') from e\n" + "\n" + "class _Unloadable(gen.Container):\n" + " # A result whose ID fails to load, after the function returned it.\n" + " def __init__(self, ctx, origin):\n" + " super().__init__(ctx)\n" + " self.origin = origin\n" + " async def id(self):\n" + " from dagger import QueryError\n" + " from dagger._exceptions import QueryErrorValue\n" + " err = QueryErrorValue('no such container' + self.origin)\n" + " raise QueryError([err], 'query')\n" + "\n" + "def _sdk_boom():\n" + " from dagger import QueryError\n" + " # The SDK raises: an API error needs an error.\n" + " return QueryError([], 'query')\n" ) return tmp_path -def _call(module_dir: pathlib.Path, request: dict) -> subprocess.CompletedProcess: +@pytest.fixture +def broken_module_dir(module_dir: pathlib.Path) -> pathlib.Path: + (module_dir / "src" / "hello" / "__init__.py").write_text( + "import json\n\nthis is not python\n" + ) + return module_dir + + +def _call( + module_dir: pathlib.Path, + request: dict, + env: dict[str, str] | None = None, +) -> subprocess.CompletedProcess: return subprocess.run( [sys.executable, "-m", "dagger.mod", "call", "--output", "out/result.json"], cwd=module_dir, @@ -104,6 +204,7 @@ def _call(module_dir: pathlib.Path, request: dict) -> subprocess.CompletedProces "PYTHONPATH": str(module_dir / "src"), "DAGGER_DEFAULT_PYTHON_PACKAGE": "hello", "DAGGER_MAIN_OBJECT": "Hello", + **(env or {}), }, input=json.dumps(request), capture_output=True, @@ -135,3 +236,574 @@ def test_command_failure_writes_nothing(module_dir: pathlib.Path): assert proc.returncode == 2 assert "boom" in proc.stderr assert not (module_dir / "out").exists() + + +def test_command_failure_reports_error_last(module_dir: pathlib.Path): + request = { + "receiverType": "Hello", + "receiverValue": "{}", + "fnName": "boom", + "fnArgs": "{}", + } + proc = _call(module_dir, request) + last = proc.stderr.rstrip("\n").split("\n")[-1] + assert last.startswith(FUNCTION_ERROR_MARKER), proc.stderr + assert json.loads(last.removeprefix(FUNCTION_ERROR_MARKER)) == "RuntimeError: boom" + + +def test_command_failure_writes_error_file(module_dir: pathlib.Path): + request = { + "receiverType": "Hello", + "receiverValue": "{}", + "fnName": "boom", + "fnArgs": "{}", + } + error_file = module_dir / "function-error" + proc = _call(module_dir, request, {FUNCTION_ERROR_PATH_ENV: str(error_file)}) + assert proc.returncode == 2 + report = json.loads(error_file.read_text()) + # The traceback names the type, so the error the engine shows needn't. + assert report["message"] == "boom" + assert report["values"]["exception.type"] == "RuntimeError" + assert report["values"]["exception.message"] == "boom" + assert "raise RuntimeError('boom')" in report["values"]["exception.stacktrace"] + assert "RuntimeError: boom" in proc.stderr + assert FUNCTION_ERROR_MARKER not in proc.stderr + # The engine shows the error; the process doesn't echo it. + echoes = [ + line + for line in proc.stderr.splitlines() + if line.strip() == "boom" or line.endswith("]: boom") + ] + assert not echoes, proc.stderr + + +def _request(fn: str, args: dict | None = None) -> dict: + return { + "receiverType": "Hello", + "receiverValue": "{}", + "fnName": fn, + "fnArgs": json.dumps(args or {}), + } + + +def _call_with_error_file( + module_dir: pathlib.Path, request: dict +) -> tuple[subprocess.CompletedProcess, dict]: + error_file = module_dir / "function-error" + proc = _call(module_dir, request, {FUNCTION_ERROR_PATH_ENV: str(error_file)}) + return proc, json.loads(error_file.read_text()) + + +def _sdk_frames(stderr: str) -> list[str]: + return [ + line + for line in stderr.splitlines() + if line.lstrip().startswith("File ") + and ("/dagger/" in line or "importlib" in line or "\n this is not python\n" in proc.stderr + assert "NameError: name 'this' is not defined" in proc.stderr + assert not _sdk_frames(proc.stderr), proc.stderr + assert "Error while importing" not in proc.stderr + assert report["message"] == "name 'this' is not defined" + + +def test_command_import_error_logs_traceback_without_error_file( + broken_module_dir: pathlib.Path, +): + proc = _call(broken_module_dir, _request("hi")) + assert proc.returncode == 2 + assert "Error while importing Python module 'hello'" in proc.stderr + assert "cli.py" in proc.stderr + + +def test_command_api_error_logs_nothing_with_error_file(module_dir: pathlib.Path): + proc, report = _call_with_error_file( + module_dir, _request("api_boom", {"origin": ORIGIN}) + ) + assert proc.returncode == 2 + # The engine shows the call that failed, with its logs. + assert proc.stderr == "", proc.stderr + assert report["message"] == "exit code: 1" + ORIGIN + values = report["values"] + assert values["_type"] == "EXEC_ERROR" + assert values["exitCode"] == 1 + assert values["exception.type"] == "dagger.ExecError" + assert "raise QueryError" in values["exception.stacktrace"] + + +def test_command_api_error_without_origin_shows_short_traceback( + module_dir: pathlib.Path, +): + proc, report = _call_with_error_file(module_dir, _request("api_boom")) + assert proc.returncode == 2 + # No call the engine shows it at: the function shows where it got it. + assert proc.stderr.startswith("Traceback (most recent call last):\n"), proc.stderr + assert "in api_boom\n raise QueryError([err], 'query')\n" in proc.stderr + assert proc.stderr.endswith("\ndagger.ExecError: exit code: 1\n"), proc.stderr + assert not _sdk_frames(proc.stderr), proc.stderr + assert "API error while executing function" not in proc.stderr + assert report["message"] == "exit code: 1" + + +def test_command_result_api_error_without_origin_shows_short_traceback( + module_dir: pathlib.Path, +): + proc, report = _call_with_error_file(module_dir, _request("unloadable")) + assert proc.returncode == 2 + # Raised loading the result, outside the function, as the API error. + assert proc.stderr.startswith("Traceback (most recent call last):\n"), proc.stderr + assert "in id\n" in proc.stderr, proc.stderr + assert proc.stderr.endswith("QueryError: no such container\n"), proc.stderr + assert not _sdk_frames(proc.stderr), proc.stderr + assert "Invalid result" not in proc.stderr + assert report["message"] == "no such container" + + +def test_command_result_api_error_logs_nothing_with_error_file( + module_dir: pathlib.Path, +): + proc, report = _call_with_error_file( + module_dir, _request("unloadable", {"origin": ORIGIN}) + ) + assert proc.returncode == 2 + assert proc.stderr == "", proc.stderr + assert report["message"] == "no such container" + ORIGIN + + +def test_command_result_api_error_without_error_file(module_dir: pathlib.Path): + proc = _call(module_dir, _request("unloadable")) + assert proc.returncode == 2 + # Old engines: as before, an invalid result. + assert "Invalid result from function" in proc.stderr, proc.stderr + + +def test_command_group_of_api_errors_logs_nothing_with_error_file( + module_dir: pathlib.Path, +): + proc, report = _call_with_error_file( + module_dir, _request("group_boom", {"origin": ORIGIN}) + ) + assert proc.returncode == 2 + # As a task group raises them: the engine shows where each comes from. + assert proc.stderr == "", proc.stderr + assert report["message"] == "exit code: 1" + ORIGIN + + +def test_command_group_of_api_errors_without_origin_shows_them( + module_dir: pathlib.Path, +): + proc, _ = _call_with_error_file(module_dir, _request("group_boom")) + assert proc.returncode == 2 + assert "in group_boom\n" in proc.stderr, proc.stderr + assert "QueryError: exit code: 1" in proc.stderr, proc.stderr + assert not _sdk_frames(proc.stderr), proc.stderr + + +def test_command_api_error_logs_traceback_without_error_file( + module_dir: pathlib.Path, +): + proc = _call(module_dir, _request("api_boom", {"origin": ORIGIN})) + assert proc.returncode == 2 + assert "API error while executing function" in proc.stderr + assert "Traceback" in proc.stderr + assert "dagger.ExecError: exit code: 1" in proc.stderr + last = proc.stderr.rstrip("\n").split("\n")[-1] + reported = json.loads(last.removeprefix(FUNCTION_ERROR_MARKER)) + assert reported == "exit code: 1" + ORIGIN + + +def test_command_success_writes_no_error_file(module_dir: pathlib.Path): + request = { + "receiverType": "Hello", + "receiverValue": "{}", + "fnName": "hi", + "fnArgs": '{"who": "you"}', + } + error_file = module_dir / "function-error" + proc = _call(module_dir, request, {FUNCTION_ERROR_PATH_ENV: str(error_file)}) + assert proc.returncode == 0, proc.stderr + assert not error_file.exists() + + +def test_error_origin_filter_strips_origins_from_logs(): + try: + raise _query_error("exit code: 1" + ORIGIN) + except QueryError as e: + record = logging.LogRecord( + "dagger.mod", logging.ERROR, __file__, 1, "failed: %s", (e,), sys.exc_info() + ) + assert ErrorOriginFilter().filter(record) + formatted = logging.Formatter().format(record) + assert "traceparent" not in formatted, formatted + assert "failed: exit code: 1" in formatted + assert formatted.rstrip().endswith("exit code: 1") + + +def test_user_traceback_leaves_out_library_frames(): + try: + json.loads("{") + except ValueError as e: + formatted = format_user_traceback(e) + assert 'json.loads("{")' in formatted, formatted + assert "decoder.py" not in formatted, formatted + assert formatted.rstrip().endswith("line 1 column 2 (char 1)"), formatted + + +def test_user_traceback_leaves_out_error_origins(): + try: + raise _query_error("exit code: 1" + ORIGIN) + except QueryError as e: + formatted = format_user_traceback(e) + assert "traceparent" not in formatted, formatted + assert formatted.endswith("QueryError: exit code: 1\n"), formatted + + +def test_user_traceback_leaves_out_generated_code(tmp_path: pathlib.Path): + generated = tmp_path / "client.py" + generated.write_text( + "# Code generated by dagger. DO NOT EDIT.\n\n" + "def call():\n" + " raise ValueError('from a client')\n" + ) + namespace: dict = {} + exec(compile(generated.read_text(), str(generated), "exec"), namespace) + try: + namespace["call"]() + except ValueError as e: + formatted = format_user_traceback(e) + assert 'namespace["call"]()' in formatted, formatted + assert "client.py" not in formatted, formatted + + +def _installed_package( + site_dir: pathlib.Path, name: str, module: str, source: str, *, local: bool +) -> None: + """Install a distribution of one module of the tb_fixture_ns namespace.""" + file = f"tb_fixture_ns/{module}.py" + (site_dir / file).parent.mkdir(parents=True, exist_ok=True) + (site_dir / file).write_text(source) + info = site_dir / f"{name}-0.1.dist-info" + info.mkdir() + metadata = f"Metadata-Version: 2.1\nName: {name}\nVersion: 0.1\n" + (info / "METADATA").write_text(metadata) + (info / "RECORD").write_text(f"{file},,\n") + if local: + url = (site_dir.parent / name).as_uri() + (info / "direct_url.json").write_text(json.dumps({"url": url, "dir_info": {}})) + + +@pytest.fixture +def site_dir(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch): + site_dir = tmp_path / "site-packages" + site_dir.mkdir() + monkeypatch.syspath_prepend(str(site_dir)) + installed = (os.path.realpath(site_dir) + os.sep,) + monkeypatch.setattr(_exceptions, "_site_dirs", lambda: installed) + _exceptions._local_files.cache_clear() + yield site_dir + _exceptions._local_files.cache_clear() + for name in list(sys.modules): + if name.startswith("tb_fixture_"): + del sys.modules[name] + + +def test_user_traceback_keeps_the_users_installed_libraries(site_dir: pathlib.Path): + # The runtime installs the module's own libraries from their directories, + # not editable, beside the packages from an index, even in one namespace. + _installed_package( + site_dir, + "tb_fixture_mine", + "mine", + "def parse(s):\n raise ValueError('empty: ' + s)\n", + local=True, + ) + _installed_package( + site_dir, + "tb_fixture_theirs", + "theirs", + "def run(fn, s):\n fn(s)\n", + local=False, + ) + importlib.invalidate_caches() + mine = importlib.import_module("tb_fixture_ns.mine") + theirs = importlib.import_module("tb_fixture_ns.theirs") + try: + theirs.run(mine.parse, "x") + except ValueError as e: + formatted = format_user_traceback(e) + assert "theirs.run(mine.parse" in formatted, formatted + assert "tb_fixture_ns/mine.py" in formatted, formatted + assert "raise ValueError('empty: ' + s)" in formatted, formatted + assert "theirs.py" not in formatted, formatted + + +def test_errors_to_show(): + shown = _query_error("no such ID") + assert errors_to_show(_query_error("exit code: 1" + ORIGIN)) is None + assert errors_to_show(shown) is shown + assert errors_to_show(KeyError("k")) is not None + group = ExceptionGroup( + "unhandled errors in a TaskGroup", + [_query_error("exit code: 1" + ORIGIN), KeyError("k"), shown], + ) + rest = errors_to_show(group) + assert isinstance(rest, ExceptionGroup) + assert [type(e) for e in rest.exceptions] == [KeyError, QueryError] + only_origins = ExceptionGroup("g", [_query_error("exit code: 1" + ORIGIN)]) + assert errors_to_show(only_origins) is None + + +def test_errors_to_show_keeps_a_group_that_loses_nothing(): + class ValidationErrors(ExceptionGroup): + pass + + group = ValidationErrors("bad input", [KeyError("k"), _query_error("no such ID")]) + assert errors_to_show(group) is group, "the user's own group type" + + +def test_user_traceback_without_user_frames(): + exc = ValueError("boom") + assert format_user_traceback(exc) == "ValueError: boom\n" + + +def test_user_traceback_of_a_group(): + def sdk_error() -> BaseException: + try: + QueryError([], "query") + except ValueError as e: + return e + raise AssertionError + + group = ExceptionGroup("unhandled errors in a TaskGroup", [sdk_error()]) + formatted = format_user_traceback(group) + assert "in sdk_error" in formatted, formatted + assert "dagger/_exceptions.py" not in formatted, formatted + assert "ValueError: Errors list is empty" in formatted, formatted + + +@pytest.mark.parametrize( + ("message", "expected"), + [("exit code: 1" + ORIGIN, True), ("no such ID", False)], +) +def test_has_error_origin(message: str, expected: bool): + assert has_error_origin(_query_error(message)) is expected + + +def _exec_error(message: str) -> QueryError: + return QueryError( + [ + QueryErrorValue( + message, + extensions={ + "_type": "EXEC_ERROR", + "cmd": ["sh", "-c", "exit 7"], + "exitCode": 7, + "stdout": "out", + "stderr": "err", + }, + ) + ], + "query", + ) + + +def _report(tmp_path: pathlib.Path, exc: BaseException) -> dict: + error_file = tmp_path / "function-error" + write_function_error(str(error_file), exc) + return json.loads(error_file.read_text()) + + +def test_write_function_error_keeps_an_api_error_whole(tmp_path: pathlib.Path): + message = "x" * 100_000 + "exit code: 7" + ORIGIN + report = _report(tmp_path, _exec_error(message)) + assert report["message"] == message, "nothing is trimmed, the origin kept" + values = report["values"] + assert values["_type"] == "EXEC_ERROR" + assert values["exitCode"] == 7 + assert values["cmd"] == ["sh", "-c", "exit 7"] + assert (values["stdout"], values["stderr"]) == ("out", "err") + assert values["exception.type"] == "dagger.ExecError" + + +def test_write_function_error_of_a_wrapped_api_error(tmp_path: pathlib.Path): + try: + try: + raise _exec_error("exit code: 7" + ORIGIN) + except QueryError as e: + msg = f"it ran a failing command: {e}" + raise RuntimeError(msg) from e + except RuntimeError as e: + report = _report(tmp_path, _wrapped(e)) + assert report["message"] == "it ran a failing command: exit code: 7" + ORIGIN + assert report["values"]["exitCode"] == 7 + assert report["values"]["exception.type"] == "RuntimeError" + + +def test_write_function_error_of_an_error_raised_handling_an_api_error( + tmp_path: pathlib.Path, +): + try: + try: + raise _exec_error("exit code: 7" + ORIGIN) + except QueryError: + msg = "lint failed" + raise RuntimeError(msg) # noqa: B904 + except RuntimeError as e: + report = _report(tmp_path, _wrapped(e)) + assert report["message"] == "lint failed" + assert "_type" not in report["values"], "not the handled exec's error" + assert report["values"]["exception.type"] == "RuntimeError" + + +def test_write_function_error_of_a_function_error_with_extra( + tmp_path: pathlib.Path, +): + try: + try: + raise _exec_error("exit code: 7" + ORIGIN) + except QueryError as e: + msg = "deploy failed" + raise FunctionError(msg, extra={"env": "prod"}) from e + except FunctionError as e: + report = _report(tmp_path, e) + assert report["values"]["extra.env"] == "prod" + assert report["values"]["exitCode"] == 7 + + +def test_write_function_error_over_the_limit(tmp_path: pathlib.Path): + message = "x" * (1 << 19) + ORIGIN + error_file = tmp_path / "function-error" + write_function_error(str(error_file), _exec_error(message)) + assert len(error_file.read_bytes()) <= 1 << 20, "the engine reads it" + report = json.loads(error_file.read_text()) + assert report["message"].endswith("..." + ORIGIN), "the origin kept" + assert report["values"]["exitCode"] == 7 + assert "exception.stacktrace" not in report["values"] + + +def test_write_function_error_of_a_module_error(tmp_path: pathlib.Path): + exc = InvalidInputError("bad input", extra={"field": "who", "bad": object()}) + report = _report(tmp_path, exc) + assert report["message"] == "bad input" + assert report["values"]["extra.field"] == "who" + assert report["values"]["extra.bad"].startswith(" QueryError: + return QueryError([QueryErrorValue(message)], "query") + + +@pytest.mark.parametrize( + ("exc", "message"), + [ + (_query_error("exit code: 3" + ORIGIN), "exit code: 3" + ORIGIN), + (InvalidInputError("bad input"), "bad input"), + (KeyError("k"), "KeyError: 'k'"), + (ValueError(), "ValueError"), + (FunctionError(""), "FunctionError"), + ], +) +def test_function_error_message(exc: BaseException, message: str): + assert function_error_message(exc) == message + + +def _wrapped(cause: BaseException) -> FunctionError: + # As Module.call wraps what a function raises. + wrapper = FunctionError(str(cause)) + wrapper.__cause__ = cause + return wrapper + + +def test_function_error_message_names_the_function_error(): + assert function_error_message(_wrapped(ValueError("boom"))) == "ValueError: boom" + + +def test_function_error_message_of_a_logged_error(): + assert function_error_message(_wrapped(ValueError("boom")), logged=True) == "boom" + assert function_error_message(_wrapped(ValueError()), logged=True) == "ValueError" + + +def test_function_error_message_reports_a_group_error_by_error(): + group = ExceptionGroup( + "unhandled errors in a TaskGroup", + [_query_error("exit code: 3" + ORIGIN), KeyError("k")], + ) + assert function_error_message(_wrapped(group)) == ( + "exit code: 3" + ORIGIN + "; KeyError: 'k'" + ) + + +def test_report_keeps_origin(capsys: pytest.CaptureFixture[str]): + report_function_error("exit code: 1\nline two" + ORIGIN) + last = capsys.readouterr().err.rstrip("\n").split("\n")[-1] + reported = json.loads(last.removeprefix(FUNCTION_ERROR_MARKER)) + assert reported == "exit code: 1\nline two" + ORIGIN + + +def test_report_truncates_but_keeps_origin(capsys: pytest.CaptureFixture[str]): + report_function_error("\x01" * 100_000 + ORIGIN) + err = capsys.readouterr().err + last = err.rstrip("\n").split("\n")[-1] + assert len(last.encode()) < 100 << 10 + reported = json.loads(last.removeprefix(FUNCTION_ERROR_MARKER)) + assert reported.endswith("..." + ORIGIN)