From 34a8a5e45357523b08e94bf9876eeaf9a55f8770 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Thu, 12 Nov 2026 17:17:38 +0000 Subject: [PATCH 01/10] sdk: fail an entrypoint call with its own error A function that failed on a generated entrypoint failed with the exit code of `python -m dagger.mod call`, the exec that runs it: "exit code: 2". Its error, and the error origin it names, stayed in the exec's log. An API error's message names the call that failed, so the process's exec became the origin instead of that call, such as a failed lint exec. The process has no current function call to return an error to, as the old runtime did with returnError. As in the Go and Java SDKs, `call` now ends its stderr with the error on a `::dagger-function-error::` line, and the generated entrypoint raises that error. The exec still fails, so a failed call is not cached. The error reported is the function's own: an exception with its type, an API error whole, and each error of a task group's group. A Dang raise carries only a message, so the error's values, such as an exec's exit code, stop at the entrypoint. The build is synced before the rescued call, so its failures still carry theirs. A module picks this up when its entrypoint is generated again. Signed-off-by: Alex Suraci --- README.md | 4 +- sdk/src/dagger/mod/__main__.py | 16 ++++- sdk/src/dagger/mod/_entrypoint.py | 27 ++++++++- sdk/src/dagger/mod/_exceptions.py | 50 +++++++++++++++- sdk/tests/mod/golden/main.dang | 18 +++++- sdk/tests/mod/golden/main_outside.dang | 18 +++++- sdk/tests/mod/test_dispatch.py | 81 +++++++++++++++++++++++++- 7 files changed, 203 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 8b015ecd..d4645f2b 100644 --- a/README.md +++ b/README.md @@ -319,7 +319,9 @@ 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. +reaches the caller as its message: an API error keeps the call it names as +its origin, but no error carries its values, such as an exec's exit code and +output, past the entrypoint. 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 8cc2204b..30e67bf9 100644 --- a/sdk/src/dagger/mod/__main__.py +++ b/sdk/src/dagger/mod/__main__.py @@ -15,7 +15,11 @@ 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 ( + ModuleError, + function_error_message, + report_function_error, +) logger = logging.getLogger(__package__) @@ -66,13 +70,21 @@ def main(argv: list[str] | None = None) -> int: args.run(args) except (ModuleError, QueryError) as e: 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 _report(args: argparse.Namespace, exc: Exception) -> None: + """Give the entrypoint a failed call's error, after everything it logged.""" + if args.run is _call: + 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 diff --git a/sdk/src/dagger/mod/_entrypoint.py b/sdk/src/dagger/mod/_entrypoint.py index 2060bff0..50e6c358 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 e1a03712..7ad9598d 100644 --- a/sdk/src/dagger/mod/_exceptions.py +++ b/sdk/src/dagger/mod/_exceptions.py @@ -1,8 +1,10 @@ import json import logging +import re +import sys import traceback from collections.abc import Mapping -from typing import Any +from typing import Any, Final import cattrs from opentelemetry.semconv.attributes.exception_attributes import ( @@ -125,6 +127,52 @@ 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) -> 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. + """ + if isinstance(exc, FunctionError) and exc.__cause__ is not None: + 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__ + + +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. + """ + if len(message) > _REPORTED_ERROR_LIMIT: + origins = "".join(_ERROR_ORIGIN.findall(message[_REPORTED_ERROR_LIMIT:])) + message = message[:_REPORTED_ERROR_LIMIT] + "..." + origins + encoded = json.dumps(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) diff --git a/sdk/tests/mod/golden/main.dang b/sdk/tests/mod/golden/main.dang index 5d3c33be..a001897b 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 230304a8..7effdfae 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 8ea5f0ab..f6d7f71d 100644 --- a/sdk/tests/mod/test_dispatch.py +++ b/sdk/tests/mod/test_dispatch.py @@ -5,8 +5,16 @@ import pytest +from dagger import QueryError +from dagger._exceptions import QueryErrorValue from dagger.mod import Module -from dagger.mod._exceptions import InvalidInputError +from dagger.mod._exceptions import ( + FUNCTION_ERROR_MARKER, + FunctionError, + InvalidInputError, + function_error_message, + report_function_error, +) pytestmark = pytest.mark.anyio @@ -135,3 +143,74 @@ 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" + + +ORIGIN = " [traceparent:" + "a" * 32 + "-" + "b" * 16 + "]" + + +def _query_error(message: str) -> 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_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) From af352868dcac986e0d15af0eb6ff5ee26a3c9b47 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 14:00:00 +0000 Subject: [PATCH 02/10] sdk: report a function's error in the engine's file An engine that implements the function error file sets DAGGER_FUNCTION_ERROR_PATH on a call's process. The process then writes the function's error there instead of the ::dagger-function-error:: line, and the engine fails the call with it as the function's own error, as it does an error returned with returnError. The exec still fails, so a failed call is not cached. The file holds {"message": ..., "values": {...}}: the error's message in full, with the origin an API error names, and the values record_exception gives a dagger.Error: the exception's type, message and stack trace, a ModuleError's extra values, and an API error's extensions, whole, also when the error wraps it. A calling module so sees an ExecError, exit code and output included, as from a runtime's function. The function's logs then say nothing the engine shows already: the error isn't logged again after the traceback, an exception the function raised is reported without its type, which the traceback names, and the error origins ([traceparent:...]) are left out of what the process logs. On an engine without the variable, the process reports the error as before. Signed-off-by: Alex Suraci --- sdk/src/dagger/mod/__main__.py | 26 +++++- sdk/src/dagger/mod/_exceptions.py | 118 +++++++++++++++++++++++++-- sdk/tests/mod/test_dispatch.py | 129 +++++++++++++++++++++++++++++- 3 files changed, 261 insertions(+), 12 deletions(-) diff --git a/sdk/src/dagger/mod/__main__.py b/sdk/src/dagger/mod/__main__.py index 30e67bf9..15161485 100644 --- a/sdk/src/dagger/mod/__main__.py +++ b/sdk/src/dagger/mod/__main__.py @@ -16,9 +16,12 @@ from dagger._exceptions import QueryError from dagger.client._session import mark_module_runtime from dagger.mod._exceptions import ( + FUNCTION_ERROR_PATH_ENV, + ErrorOriginFilter, ModuleError, function_error_message, report_function_error, + write_function_error, ) logger = logging.getLogger(__package__) @@ -66,10 +69,16 @@ 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 as e: @@ -79,9 +88,20 @@ def main(argv: list[str] | None = None) -> int: 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 entrypoint a failed call's error, after everything it logged.""" - if args.run is _call: + """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)) diff --git a/sdk/src/dagger/mod/_exceptions.py b/sdk/src/dagger/mod/_exceptions.py index 7ad9598d..870b7ce6 100644 --- a/sdk/src/dagger/mod/_exceptions.py +++ b/sdk/src/dagger/mod/_exceptions.py @@ -1,5 +1,6 @@ import json import logging +import pathlib import re import sys import traceback @@ -141,13 +142,17 @@ def log_exception_only( _ERROR_ORIGIN: Final = re.compile(r"\s*\[traceparent:[0-9a-f]{32}-[0-9a-f]{16}\]") -def function_error_message(exc: BaseException) -> str: +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. + 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) @@ -156,6 +161,105 @@ def function_error_message(exc: BaseException) -> str: 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 _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. + """ + reported = exc + if isinstance(exc, FunctionError) and exc.__cause__ is not None: + reported = exc.__cause__ + report = { + # The traceback, which names the exception's type, is already in + # the function's logs. + "message": function_error_message(exc, logged=True), + "values": { + key: _json_value(value) + for key, value in function_error_values(reported).items() + }, + } + encoded = json.dumps(report, ensure_ascii=False) + pathlib.Path(path).write_text(encoded, encoding="utf-8") + + +def function_error_values(exc: BaseException) -> dict[str, Any]: + """The values of the error a failed call reports for `exc`. + + The same as `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. + The API error may be one the exception wraps, as one that adds to its + message does. + """ + attrs: dict[str, Any] = _exception_attributes(exc) + if isinstance(exc, ModuleError) and exc.extra: + extra = {f"extra.{key}": val for key, val in exc.extra.items()} + attrs = {**extra, **attrs} + if (api_error := _wrapped_query_error(exc)) is not None: + attrs.update(api_error.error.extensions) + return attrs + + +def _wrapped_query_error(exc: BaseException) -> QueryError | None: + """The API error exc is or wraps, if any.""" + seen: set[int] = set() + cur: BaseException | None = exc + while cur is not None and id(cur) not in seen: + if isinstance(cur, QueryError): + return cur + seen.add(id(cur)) + cur = cur.__cause__ or (None if cur.__suppress_context__ else cur.__context__) + 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. @@ -163,12 +267,10 @@ def report_function_error(message: str) -> None: 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. + origin, not the process. An engine that gives the process a file for the + error (FUNCTION_ERROR_PATH_ENV) gets it there instead. """ - if len(message) > _REPORTED_ERROR_LIMIT: - origins = "".join(_ERROR_ORIGIN.findall(message[_REPORTED_ERROR_LIMIT:])) - message = message[:_REPORTED_ERROR_LIMIT] + "..." + origins - encoded = json.dumps(message, ensure_ascii=False) + encoded = json.dumps(_limit(message), ensure_ascii=False) sys.stderr.write(f"\n{FUNCTION_ERROR_MARKER}{encoded}\n") sys.stderr.flush() @@ -210,7 +312,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/tests/mod/test_dispatch.py b/sdk/tests/mod/test_dispatch.py index f6d7f71d..5996fcf5 100644 --- a/sdk/tests/mod/test_dispatch.py +++ b/sdk/tests/mod/test_dispatch.py @@ -1,4 +1,5 @@ import json +import logging import pathlib import subprocess import sys @@ -10,10 +11,13 @@ from dagger.mod import Module from dagger.mod._exceptions import ( FUNCTION_ERROR_MARKER, + FUNCTION_ERROR_PATH_ENV, + ErrorOriginFilter, FunctionError, InvalidInputError, function_error_message, report_function_error, + write_function_error, ) pytestmark = pytest.mark.anyio @@ -103,7 +107,11 @@ def module_dir(tmp_path: pathlib.Path) -> pathlib.Path: return tmp_path -def _call(module_dir: pathlib.Path, request: dict) -> subprocess.CompletedProcess: +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, @@ -112,6 +120,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, @@ -158,6 +167,119 @@ def test_command_failure_reports_error_last(module_dir: pathlib.Path): 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 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 _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 = "\x01" * 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_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(" Date: Sun, 22 Nov 2026 15:00:00 +0000 Subject: [PATCH 03/10] sdk: keep a function's error report readable A report over the engine's 1 MiB limit is dropped whole, so trim it to fit: the stack trace goes first, then the message and string values are cut. Take an API error's values only from the exception it was raised from, not one it was raised while handling, and keep a FunctionError's own extra values beside its cause's. Signed-off-by: Alex Suraci --- sdk/src/dagger/mod/_exceptions.py | 73 +++++++++++++++++++++---------- sdk/tests/mod/test_dispatch.py | 44 ++++++++++++++++++- 2 files changed, 92 insertions(+), 25 deletions(-) diff --git a/sdk/src/dagger/mod/_exceptions.py b/sdk/src/dagger/mod/_exceptions.py index 870b7ce6..01c5bdb2 100644 --- a/sdk/src/dagger/mod/_exceptions.py +++ b/sdk/src/dagger/mod/_exceptions.py @@ -205,49 +205,74 @@ def write_function_error(path: str, exc: BaseException) -> None: message names the call that failed, so that call stays the error's origin; any other error comes from the function call. """ - reported = exc + # 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: - reported = exc.__cause__ - report = { - # The traceback, which names the exception's type, is already in - # the function's logs. - "message": function_error_message(exc, logged=True), - "values": { - key: _json_value(value) - for key, value in function_error_values(reported).items() - }, - } - encoded = json.dumps(report, ensure_ascii=False) + # 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`. The same as `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. - The API error may be one the exception wraps, as one that adds to its - message does. + The API error may 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] = _exception_attributes(exc) - if isinstance(exc, ModuleError) and exc.extra: - extra = {f"extra.{key}": val for key, val in exc.extra.items()} - attrs = {**extra, **attrs} - if (api_error := _wrapped_query_error(exc)) is not None: - attrs.update(api_error.error.extensions) + 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 _wrapped_query_error(exc: BaseException) -> QueryError | None: - """The API error exc is or wraps, if any.""" +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: BaseException | None = exc + 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__ or (None if cur.__suppress_context__ else cur.__context__) + cur = cur.__cause__ return None diff --git a/sdk/tests/mod/test_dispatch.py b/sdk/tests/mod/test_dispatch.py index 5996fcf5..313fe124 100644 --- a/sdk/tests/mod/test_dispatch.py +++ b/sdk/tests/mod/test_dispatch.py @@ -246,7 +246,7 @@ def _report(tmp_path: pathlib.Path, exc: BaseException) -> dict: def test_write_function_error_keeps_an_api_error_whole(tmp_path: pathlib.Path): - message = "\x01" * 100_000 + "exit code: 7" + ORIGIN + 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"] @@ -271,6 +271,48 @@ def test_write_function_error_of_a_wrapped_api_error(tmp_path: pathlib.Path): 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) From 775e8d0f90518bea96b1ec097e3f7b36f538b380 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 15:10:00 +0000 Subject: [PATCH 04/10] sdk: say how a report's values differ function_error_values also takes an API error's values from the exception it was raised from, which record_exception does not. Signed-off-by: Alex Suraci --- sdk/src/dagger/mod/_exceptions.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/sdk/src/dagger/mod/_exceptions.py b/sdk/src/dagger/mod/_exceptions.py index 01c5bdb2..6d2eea7f 100644 --- a/sdk/src/dagger/mod/_exceptions.py +++ b/sdk/src/dagger/mod/_exceptions.py @@ -242,12 +242,13 @@ def _function_error_report(message: str, values: dict[str, Any]) -> str: def function_error_values(exc: BaseException) -> dict[str, Any]: """The values of the error a failed call reports for `exc`. - The same as `record_exception` gives its `dagger.Error`: the exception's - type, message and stack trace, a ModuleError's `extra` values, and an API + 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. - The API error may 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. + 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): From a0121427c0660e99553b3f89f9e36fb849fa332a Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 16:00:00 +0000 Subject: [PATCH 05/10] README: error values reach callers on new engines On an engine that gives the call's process DAGGER_FUNCTION_ERROR_PATH, a function's error keeps its values; only older engines get the message alone. Signed-off-by: Alex Suraci --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d4645f2b..97d5b636 100644 --- a/README.md +++ b/README.md @@ -318,10 +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 its message: an API error keeps the call it names as -its origin, but no error carries its values, such as an exec's exit code and -output, past the entrypoint. +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 From e711bad781a821b30cbb65acb67d7149f58e88ae Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 05:14:25 +0000 Subject: [PATCH 06/10] sdk: log no API error a call reports in a file When the engine gives a call's process DAGGER_FUNCTION_ERROR_PATH, an API error that escapes a function is no longer logged with its traceback. The engine fails the call with the error the file reports and shows its origin, the call that failed with its logs; the traceback ending in `dagger.ExecError: exit code: 1` only dominated the output. The report keeps the full values, stack trace included, and old engines still get the log and the marker. Signed-off-by: Alex Suraci --- sdk/src/dagger/mod/__main__.py | 11 ++++++--- sdk/src/dagger/mod/_module.py | 14 +++++++---- sdk/tests/mod/test_dispatch.py | 43 ++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/sdk/src/dagger/mod/__main__.py b/sdk/src/dagger/mod/__main__.py index 15161485..d458570f 100644 --- a/sdk/src/dagger/mod/__main__.py +++ b/sdk/src/dagger/mod/__main__.py @@ -136,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) + mod = load_module() + if error_file: + # The engine fails the call with the API error the file reports, and + # shows where it comes from: the call that failed, with its logs. + mod.log_api_errors = False + return await mod.dispatch(request) def _exit(code: int) -> None: diff --git a/sdk/src/dagger/mod/_module.py b/sdk/src/dagger/mod/_module.py index a5c4968b..88bb7eda 100644 --- a/sdk/src/dagger/mod/_module.py +++ b/sdk/src/dagger/mod/_module.py @@ -99,6 +99,11 @@ 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 an API error that escapes a function is logged with its + # traceback. A call that reports its error in the file the engine + # gives it turns this off: the engine shows the error's origin, the + # call that failed with its logs, so the traceback only adds noise. + self.log_api_errors = True @property def main_cls(self) -> type[ObjectType]: @@ -409,10 +414,11 @@ async def call(self, func: Func[P, R], *args: P.args, **kwargs: P.kwargs) -> R: 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), - ) + if self.log_api_errors: + logger.exception( + "API error while executing function", + exc_info=(type(e), e, tb), + ) # Preserve API error so it's properly propagated. raise e from None except Exception as e: diff --git a/sdk/tests/mod/test_dispatch.py b/sdk/tests/mod/test_dispatch.py index 313fe124..5ec61ecd 100644 --- a/sdk/tests/mod/test_dispatch.py +++ b/sdk/tests/mod/test_dispatch.py @@ -103,6 +103,14 @@ 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) -> 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" + " raise QueryError([QueryErrorValue('exit code: 1', extensions=ext)],\n" + " 'query')\n" ) return tmp_path @@ -194,6 +202,41 @@ def test_command_failure_writes_error_file(module_dir: pathlib.Path): assert not echoes, proc.stderr +API_BOOM = { + "receiverType": "Hello", + "receiverValue": "{}", + "fnName": "api_boom", + "fnArgs": "{}", +} + + +def test_command_api_error_logs_nothing_with_error_file(module_dir: pathlib.Path): + error_file = module_dir / "function-error" + proc = _call(module_dir, API_BOOM, {FUNCTION_ERROR_PATH_ENV: str(error_file)}) + assert proc.returncode == 2 + # The engine shows the call that failed, with its logs. + assert proc.stderr == "", proc.stderr + report = json.loads(error_file.read_text()) + assert report["message"] == "exit code: 1" + 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_logs_traceback_without_error_file( + module_dir: pathlib.Path, +): + proc = _call(module_dir, API_BOOM) + 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] + assert json.loads(last.removeprefix(FUNCTION_ERROR_MARKER)) == "exit code: 1" + + def test_command_success_writes_no_error_file(module_dir: pathlib.Path): request = { "receiverType": "Hello", From a67b7a27027be02fcd62c47e5c1340a84adaa3da Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 05:55:42 +0000 Subject: [PATCH 07/10] sdk: show a short traceback of the user's code When the engine gives a call's process DAGGER_FUNCTION_ERROR_PATH, a function's own exception, and an error importing the module's code, are shown as Python shows an uncaught exception, with only the user's frames: the SDK's, the generated clients', the standard library's and installed packages' frames go, in each chained exception too, and so does the "Unhandled exception while executing function" log line above it. The error file keeps the whole traceback. An API error that names no origin, such as an ID that fails to load, is shown the same way: the engine shows no call it comes from. One that names its origin is still not shown, the engine showing the call that failed with its logs. Old engines keep the full logs. Signed-off-by: Alex Suraci --- sdk/src/dagger/mod/__main__.py | 10 +- sdk/src/dagger/mod/_exceptions.py | 101 +++++++++++++ sdk/src/dagger/mod/_module.py | 35 +++-- sdk/src/dagger/mod/cli.py | 27 +++- sdk/tests/mod/test_dispatch.py | 227 +++++++++++++++++++++++++++--- 5 files changed, 358 insertions(+), 42 deletions(-) diff --git a/sdk/src/dagger/mod/__main__.py b/sdk/src/dagger/mod/__main__.py index d458570f..9f546c55 100644 --- a/sdk/src/dagger/mod/__main__.py +++ b/sdk/src/dagger/mod/__main__.py @@ -146,11 +146,11 @@ def _call(args: argparse.Namespace) -> None: async def _dispatch(request: dict[str, Any], error_file: bool) -> Any: from dagger.mod.cli import load_module - mod = load_module() - if error_file: - # The engine fails the call with the API error the file reports, and - # shows where it comes from: the call that failed, with its logs. - mod.log_api_errors = False + # 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) diff --git a/sdk/src/dagger/mod/_exceptions.py b/sdk/src/dagger/mod/_exceptions.py index 6d2eea7f..98d30a22 100644 --- a/sdk/src/dagger/mod/_exceptions.py +++ b/sdk/src/dagger/mod/_exceptions.py @@ -1,10 +1,16 @@ +import functools 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 types import FrameType from typing import Any, Final import cattrs @@ -189,6 +195,101 @@ def filter(self, record: logging.LogRecord) -> bool: 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 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 installed packages 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 + return not os.path.realpath(filename).startswith(_library_paths()) + + +@functools.cache +def _library_paths() -> tuple[str, ...]: + """The directories of the standard library and the installed packages.""" + paths = { + sysconfig.get_path(name) + for name in ("stdlib", "platstdlib", "purelib", "platlib") + } + paths.update(site.getsitepackages()) + paths.add(site.getusersitepackages()) + return tuple(os.path.realpath(path) + os.sep for path in paths if path) + + def _limit(message: str) -> str: if len(message) > _REPORTED_ERROR_LIMIT: origins = "".join(_ERROR_ORIGIN.findall(message[_REPORTED_ERROR_LIMIT:])) diff --git a/sdk/src/dagger/mod/_module.py b/sdk/src/dagger/mod/_module.py index 88bb7eda..c45e702d 100644 --- a/sdk/src/dagger/mod/_module.py +++ b/sdk/src/dagger/mod/_module.py @@ -38,7 +38,9 @@ ModuleError, ObjectNotFoundError, RegistrationError, + has_error_origin, log_exception_only, + print_user_traceback, transform_error, ) from dagger.mod._naming import ModuleNames, module_names @@ -99,11 +101,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 an API error that escapes a function is logged with its - # traceback. A call that reports its error in the file the engine - # gives it turns this off: the engine shows the error's origin, the - # call that failed with its logs, so the traceback only adds noise. - self.log_api_errors = 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]: @@ -408,24 +411,32 @@ 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 - if self.log_api_errors: + if not self.short_tracebacks: + tb = e.__traceback__ + # Exclude the line in "try" above + if tb: + tb = tb.tb_next logger.exception( "API error while executing function", exc_info=(type(e), e, tb), ) + elif not has_error_origin(e): + # The engine shows no call this error comes from, such as an + # ID that fails to load: show where the function got it. + print_user_traceback(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") + if self.short_tracebacks: + print_user_traceback(e) + else: + # Logging the exception will show the full stack trace on + # stderr. + logger.exception("Unhandled exception while executing function") raise FunctionError(str(e)) from e return result diff --git a/sdk/src/dagger/mod/cli.py b/sdk/src/dagger/mod/cli.py index 2dfe9511..01d0361e 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/test_dispatch.py b/sdk/tests/mod/test_dispatch.py index 5ec61ecd..d090bfaa 100644 --- a/sdk/tests/mod/test_dispatch.py +++ b/sdk/tests/mod/test_dispatch.py @@ -15,13 +15,17 @@ ErrorOriginFilter, FunctionError, InvalidInputError, + 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: @@ -104,17 +108,39 @@ def module_dir(tmp_path: pathlib.Path) -> pathlib.Path: " def boom(self) -> str:\n" " raise RuntimeError('boom')\n" " @function\n" - " def api_boom(self) -> str:\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" - " raise QueryError([QueryErrorValue('exit code: 1', extensions=ext)],\n" - " 'query')\n" + " err = QueryErrorValue('exit code: 1' + origin, extensions=ext)\n" + " raise QueryError([err], 'query')\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" + "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 +@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, @@ -202,22 +228,111 @@ def test_command_failure_writes_error_file(module_dir: pathlib.Path): assert not echoes, proc.stderr -API_BOOM = { - "receiverType": "Hello", - "receiverValue": "{}", - "fnName": "api_boom", - "fnArgs": "{}", -} +def _request(fn: str, args: dict | None = None) -> dict: + return { + "receiverType": "Hello", + "receiverValue": "{}", + "fnName": fn, + "fnArgs": json.dumps(args or {}), + } -def test_command_api_error_logs_nothing_with_error_file(module_dir: pathlib.Path): +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, API_BOOM, {FUNCTION_ERROR_PATH_ENV: str(error_file)}) + 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 - report = json.loads(error_file.read_text()) - assert report["message"] == "exit code: 1" + assert report["message"] == "exit code: 1" + ORIGIN values = report["values"] assert values["_type"] == "EXEC_ERROR" assert values["exitCode"] == 1 @@ -225,16 +340,31 @@ def test_command_api_error_logs_nothing_with_error_file(module_dir: pathlib.Path 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_api_error_logs_traceback_without_error_file( module_dir: pathlib.Path, ): - proc = _call(module_dir, API_BOOM) + 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] - assert json.loads(last.removeprefix(FUNCTION_ERROR_MARKER)) == "exit code: 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): @@ -264,6 +394,70 @@ def test_error_origin_filter_strips_origins_from_logs(): 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 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( [ @@ -365,9 +559,6 @@ def test_write_function_error_of_a_module_error(tmp_path: pathlib.Path): assert report["values"]["exception.type"] == "InvalidInputError" -ORIGIN = " [traceparent:" + "a" * 32 + "-" + "b" * 16 + "]" - - def _query_error(message: str) -> QueryError: return QueryError([QueryErrorValue(message)], "query") From d8e50920464a78b26f7a62a61ddb6ba0946c1ad5 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 06:19:43 +0000 Subject: [PATCH 08/10] sdk: keep the user's libraries in a traceback The short traceback left out every frame under site-packages, but the runtime installs the members of a module's workspace, the user's own libraries among them, from their directories, not editable: an exception raised in one lost the line that raised it. Frames of a package installed from a local directory (PEP 610's direct_url.json) are the user's. An API error a task group raises arrives in an ExceptionGroup: the errors whose origin the engine shows are left out of it too, and nothing is shown when none is left. Signed-off-by: Alex Suraci --- sdk/src/dagger/mod/_exceptions.py | 81 +++++++++++++++++++---- sdk/src/dagger/mod/_module.py | 50 ++++++++------ sdk/tests/mod/test_dispatch.py | 104 +++++++++++++++++++++++++++++- 3 files changed, 201 insertions(+), 34 deletions(-) diff --git a/sdk/src/dagger/mod/_exceptions.py b/sdk/src/dagger/mod/_exceptions.py index 98d30a22..fc13a6c2 100644 --- a/sdk/src/dagger/mod/_exceptions.py +++ b/sdk/src/dagger/mod/_exceptions.py @@ -1,4 +1,5 @@ import functools +import importlib.metadata import json import linecache import logging @@ -9,7 +10,7 @@ import sys import sysconfig import traceback -from collections.abc import Mapping +from collections.abc import Iterable, Mapping from types import FrameType from typing import Any, Final @@ -205,6 +206,20 @@ def has_error_origin(exc: QueryError) -> bool: 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): + _, rest = exc.split(lambda e: isinstance(e, QueryError) and has_error_origin(e)) + return rest + return exc + + def print_user_traceback(exc: BaseException) -> None: """Show an exception as Python shows an uncaught one, in the user's code. @@ -221,10 +236,11 @@ def format_user_traceback(exc: BaseException) -> str: 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 installed packages 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. + 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()) @@ -275,21 +291,58 @@ def _is_user_frame(frame: FrameType) -> bool: return False if linecache.getline(filename, 1).startswith(_GENERATED_HEADER): return False - return not os.path.realpath(filename).startswith(_library_paths()) + 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 module.partition(".")[0] in _local_packages() + 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 _library_paths() -> tuple[str, ...]: - """The directories of the standard library and the installed packages.""" - paths = { - sysconfig.get_path(name) - for name in ("stdlib", "platstdlib", "purelib", "platlib") - } - paths.update(site.getsitepackages()) - paths.add(site.getusersitepackages()) +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_packages() -> frozenset[str]: + """The top-level packages installed from a local directory.""" + return frozenset( + top + for top, dists in importlib.metadata.packages_distributions().items() + if any(_installed_from_directory(dist) for dist in dists) + ) + + +@functools.cache +def _installed_from_directory(name: str) -> bool: + """Whether a distribution was installed from a local directory (PEP 610).""" + try: + text = importlib.metadata.distribution(name).read_text("direct_url.json") + info = json.loads(text or "{}") + except (importlib.metadata.PackageNotFoundError, 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:])) diff --git a/sdk/src/dagger/mod/_module.py b/sdk/src/dagger/mod/_module.py index c45e702d..648a7681 100644 --- a/sdk/src/dagger/mod/_module.py +++ b/sdk/src/dagger/mod/_module.py @@ -38,6 +38,7 @@ ModuleError, ObjectNotFoundError, RegistrationError, + errors_to_show, has_error_origin, log_exception_only, print_user_traceback, @@ -413,34 +414,45 @@ async def call(self, func: Func[P, R], *args: P.args, **kwargs: P.kwargs) -> R: except QueryError as e: # Exclude the underlying TransportQueryError to reduce noise e.__cause__ = None - if not self.short_tracebacks: - tb = e.__traceback__ - # Exclude the line in "try" above - if tb: - tb = tb.tb_next - logger.exception( - "API error while executing function", - exc_info=(type(e), e, tb), - ) - elif not has_error_origin(e): - # The engine shows no call this error comes from, such as an - # ID that fails to load: show where the function got it. - print_user_traceback(e) + 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: - if self.short_tracebacks: - print_user_traceback(e) - else: - # 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: + # 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. + if not has_error_origin(e): + print_user_traceback(e) + 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) diff --git a/sdk/tests/mod/test_dispatch.py b/sdk/tests/mod/test_dispatch.py index d090bfaa..94203a70 100644 --- a/sdk/tests/mod/test_dispatch.py +++ b/sdk/tests/mod/test_dispatch.py @@ -1,5 +1,7 @@ +import importlib import json import logging +import os import pathlib import subprocess import sys @@ -8,13 +10,14 @@ from dagger import QueryError from dagger._exceptions import QueryErrorValue -from dagger.mod import Module +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, @@ -116,6 +119,12 @@ def module_dir(tmp_path: pathlib.Path) -> pathlib.Path: " 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 sdk_boom(self) -> str:\n" " return _sdk_boom()\n" " @function\n" @@ -354,6 +363,28 @@ def test_command_api_error_without_origin_shows_short_traceback( assert report["message"] == "exit code: 1" +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, ): @@ -430,6 +461,77 @@ def test_user_traceback_leaves_out_generated_code(tmp_path: pathlib.Path): assert "client.py" not in formatted, formatted +def _installed_package( + site_dir: pathlib.Path, name: str, source: str, *, local: bool +) -> None: + (site_dir / name).mkdir(parents=True) + (site_dir / name / "__init__.py").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 / "top_level.txt").write_text(f"{name}\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_packages.cache_clear() + yield site_dir + _exceptions._local_packages.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. + _installed_package( + site_dir, + "tb_fixture_mine", + "def parse(s):\n raise ValueError('empty: ' + s)\n", + local=True, + ) + _installed_package( + site_dir, "tb_fixture_theirs", "def run(fn, s):\n fn(s)\n", local=False + ) + importlib.invalidate_caches() + mine = importlib.import_module("tb_fixture_mine") + theirs = importlib.import_module("tb_fixture_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_mine" in formatted, formatted + assert "raise ValueError('empty: ' + s)" in formatted, formatted + assert "tb_fixture_theirs" 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_user_traceback_without_user_frames(): exc = ValueError("boom") assert format_user_traceback(exc) == "ValueError: boom\n" From c5e6697edf8b4adbe72546016dd3665ce8f96a00 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 06:33:48 +0000 Subject: [PATCH 09/10] sdk: judge an installed frame by its file A namespace package is shared by the distributions in it, so a library from an index in the same namespace as a local workspace member counted as the user's: a frame is the user's when its file is one a distribution installed from a local directory installed. A group that loses no API error is shown as it is, keeping the user's own group type, rather than as the plain group split derives. Signed-off-by: Alex Suraci --- sdk/src/dagger/mod/_exceptions.py | 31 +++++++++++++----------- sdk/tests/mod/test_dispatch.py | 39 +++++++++++++++++++++---------- 2 files changed, 45 insertions(+), 25 deletions(-) diff --git a/sdk/src/dagger/mod/_exceptions.py b/sdk/src/dagger/mod/_exceptions.py index fc13a6c2..5f5446d2 100644 --- a/sdk/src/dagger/mod/_exceptions.py +++ b/sdk/src/dagger/mod/_exceptions.py @@ -215,8 +215,11 @@ def errors_to_show(exc: BaseException) -> BaseException | None: if isinstance(exc, QueryError): return None if has_error_origin(exc) else exc if isinstance(exc, BaseExceptionGroup): - _, rest = exc.split(lambda e: isinstance(e, QueryError) and has_error_origin(e)) - return rest + 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 @@ -295,7 +298,7 @@ def _is_user_frame(frame: FrameType) -> bool: 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 module.partition(".")[0] in _local_packages() + return path in _local_files() return not path.startswith(_dirs("stdlib", "platstdlib")) @@ -319,22 +322,24 @@ def _as_dirs(paths: Iterable[str]) -> tuple[str, ...]: @functools.cache -def _local_packages() -> frozenset[str]: - """The top-level packages installed from a local directory.""" +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( - top - for top, dists in importlib.metadata.packages_distributions().items() - if any(_installed_from_directory(dist) for dist in dists) + 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 () ) -@functools.cache -def _installed_from_directory(name: str) -> bool: +def _installed_from_directory(dist: importlib.metadata.Distribution) -> bool: """Whether a distribution was installed from a local directory (PEP 610).""" try: - text = importlib.metadata.distribution(name).read_text("direct_url.json") - info = json.loads(text or "{}") - except (importlib.metadata.PackageNotFoundError, ValueError): + info = json.loads(dist.read_text("direct_url.json") or "{}") + except ValueError: return False return ( isinstance(info, dict) diff --git a/sdk/tests/mod/test_dispatch.py b/sdk/tests/mod/test_dispatch.py index 94203a70..c1309725 100644 --- a/sdk/tests/mod/test_dispatch.py +++ b/sdk/tests/mod/test_dispatch.py @@ -462,15 +462,17 @@ def test_user_traceback_leaves_out_generated_code(tmp_path: pathlib.Path): def _installed_package( - site_dir: pathlib.Path, name: str, source: str, *, local: bool + site_dir: pathlib.Path, name: str, module: str, source: str, *, local: bool ) -> None: - (site_dir / name).mkdir(parents=True) - (site_dir / name / "__init__.py").write_text(source) + """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 / "top_level.txt").write_text(f"{name}\n") + (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": {}})) @@ -483,9 +485,9 @@ def site_dir(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.syspath_prepend(str(site_dir)) installed = (os.path.realpath(site_dir) + os.sep,) monkeypatch.setattr(_exceptions, "_site_dirs", lambda: installed) - _exceptions._local_packages.cache_clear() + _exceptions._local_files.cache_clear() yield site_dir - _exceptions._local_packages.cache_clear() + _exceptions._local_files.cache_clear() for name in list(sys.modules): if name.startswith("tb_fixture_"): del sys.modules[name] @@ -493,27 +495,32 @@ def site_dir(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch): 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. + # 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", "def run(fn, s):\n fn(s)\n", local=False + 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_mine") - theirs = importlib.import_module("tb_fixture_theirs") + 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_mine" in formatted, formatted + assert "tb_fixture_ns/mine.py" in formatted, formatted assert "raise ValueError('empty: ' + s)" in formatted, formatted - assert "tb_fixture_theirs" not in formatted, formatted + assert "theirs.py" not in formatted, formatted def test_errors_to_show(): @@ -532,6 +539,14 @@ def test_errors_to_show(): 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" From 1927020b371bf86afaa8463d67978228210d43d1 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 07:00:47 +0000 Subject: [PATCH 10/10] sdk: show API errors raised outside a function An API error can fail a call before or after the function runs: naming the module's declarations, or loading its result's ID. With the function error file, `dispatch` now shows any API error the call fails with as one from the function is: a short traceback when it names no origin, nothing when the engine shows where it comes from. Such an error goes on as the API error, not wrapped as an invalid input or result, so the engine gets its origin. Old engines keep the wrapping and its log. Signed-off-by: Alex Suraci --- sdk/src/dagger/mod/_module.py | 45 ++++++++++++++------ sdk/tests/mod/test_dispatch.py | 75 +++++++++++++++++++++++++++++++++- 2 files changed, 107 insertions(+), 13 deletions(-) diff --git a/sdk/src/dagger/mod/_module.py b/sdk/src/dagger/mod/_module.py index 648a7681..6da7f0a7 100644 --- a/sdk/src/dagger/mod/_module.py +++ b/sdk/src/dagger/mod/_module.py @@ -307,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, @@ -333,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, @@ -428,11 +449,7 @@ async def call(self, func: Func[P, R], *args: P.args, **kwargs: P.kwargs) -> R: def _show_api_error(self, e: QueryError) -> None: """Show an API error a function raised in the function's logs.""" if self.short_tracebacks: - # 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. - if not has_error_origin(e): - print_user_traceback(e) + # `dispatch` shows it, as any API error the call fails with. return tb = e.__traceback__ # Exclude the line in "try" in `call` @@ -481,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, @@ -525,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/tests/mod/test_dispatch.py b/sdk/tests/mod/test_dispatch.py index c1309725..e0d4cb69 100644 --- a/sdk/tests/mod/test_dispatch.py +++ b/sdk/tests/mod/test_dispatch.py @@ -85,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", @@ -102,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" @@ -125,6 +152,9 @@ def module_dir(tmp_path: pathlib.Path) -> pathlib.Path: " 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" @@ -134,6 +164,17 @@ def module_dir(tmp_path: pathlib.Path) -> pathlib.Path: " 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" @@ -363,6 +404,38 @@ def test_command_api_error_without_origin_shows_short_traceback( 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, ):