From 11501071c7cd908fe5ccb677a89fce7a791b1051 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 23:10:53 +0000 Subject: [PATCH 1/2] feat: report function errors to the engine A failed call fails with its own error: in the engine's function error file (DAGGER_FUNCTION_ERROR_PATH, dagger/dagger#15249), with the values of the API error it was raised from, and a short trace of the module's own frames in its logs, in Ruby's own form; nothing for an API error whose origin the engine shows. On an older engine, Ruby's full trace and a ::dagger-function-error:: marker line, which the generated entrypoint raises. The entrypoint now marks its function's exec, and no other, with DAGGER_MODULE_CALL_DIGEST: without it, no exec was the module process, and the function's logs and errors rendered on the dispatcher's exec. It declares the gems' install as prebuild, so the engine builds it as the module's build. Signed-off-by: Alex Suraci --- .dagger/modules/e2e/sdk/entrypoint/main.dang | 45 +++- .dagger/modules/e2e/sdk/exe/dagger-mod | 15 +- .dagger/modules/e2e/sdk/lib/dagger/mod.rb | 1 + .dagger/modules/e2e/sdk/lib/dagger/mod/cli.rb | 27 +- .../e2e/sdk/lib/dagger/mod/dispatch.rb | 17 +- .../e2e/sdk/lib/dagger/mod/entrypoint.rb | 45 +++- .../e2e/sdk/lib/dagger/mod/error_report.rb | 250 ++++++++++++++++++ .../modules/e2e/sdk/lib/dagger/mod/errors.rb | 2 - .dagger/modules/e2e/sdk/sig/mod/mod.rbs | 51 +++- AGENTS.md | 7 +- CHANGELOG.md | 6 + README.md | 14 +- hack/designs/ruby-sdk-design.md | 34 ++- sdk/exe/dagger-mod | 15 +- sdk/lib/dagger/mod.rb | 1 + sdk/lib/dagger/mod/cli.rb | 27 +- sdk/lib/dagger/mod/dispatch.rb | 17 +- sdk/lib/dagger/mod/entrypoint.rb | 45 +++- sdk/lib/dagger/mod/error_report.rb | 250 ++++++++++++++++++ sdk/lib/dagger/mod/errors.rb | 2 - sdk/sig/mod/mod.rbs | 51 +++- test/golden/mod/main-sources.dang | 45 +++- test/golden/mod/main.dang | 45 +++- test/mod/dispatch_test.rb | 43 ++- test/mod/entrypoint_test.rb | 36 ++- test/mod/error_report_test.rb | 188 +++++++++++++ 26 files changed, 1180 insertions(+), 99 deletions(-) create mode 100644 .dagger/modules/e2e/sdk/lib/dagger/mod/error_report.rb create mode 100644 sdk/lib/dagger/mod/error_report.rb create mode 100644 test/mod/error_report_test.rb diff --git a/.dagger/modules/e2e/sdk/entrypoint/main.dang b/.dagger/modules/e2e/sdk/entrypoint/main.dang index 864d426..8fba22b 100644 --- a/.dagger/modules/e2e/sdk/entrypoint/main.dang +++ b/.dagger/modules/e2e/sdk/entrypoint/main.dang @@ -21,6 +21,13 @@ type Entrypoint implements ModuleEntrypoint { ModuleTypes().all } + # The module with its gems installed, which every call runs: the engine + # builds it ahead of a call, as the module's build, so a failed install + # shows as the build's, with Bundler's output. + pub prebuild: File! { + runtime.file("Gemfile.lock") + } + pub call( receiverType: String!, receiverValue: JSON, @@ -33,17 +40,49 @@ type Entrypoint implements ModuleEntrypoint { receiverValue: receiverValue, fnName: fnName, fnArgs: fnArgs, - callDigest: callDigest, moduleSource: currentModule.source.id, }}) - let result = runtime + # A failed install stays out of the rescue below, so it fails the call + # with its own error. An engine that builds prebuild first fails the + # call before it gets here. + let installed = runtime.sync + let result = installed .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + # The exec is cached on its own recipe, which holds neither the + # call's arguments nor its cache policy; the engine's digest of the + # call does (dagger/dagger#14491). It also marks this exec, and no + # other, as the module process, the one that runs the function. + .withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "") .withExec(["ruby", "-rbundler/setup", "sdk/exe/dagger-mod", "call", "--output", "/dagger/result.json"], stdin: request) .file("/dagger/result.json") - .contents + .contents rescue { + err: GraphQLError => raiseFunctionError(err) + } (result :: JSON!) } + # An engine that gives the module process a file for the function's + # error (DAGGER_FUNCTION_ERROR_PATH) puts the error the process wrote + # there in its exec's error, and fails the call with it, values and all: + # the exec's error is raised as it is. Otherwise, as with an older engine + # or a file the process couldn't write, the exec error carries the end + # of the process's stderr, where its last marker line holds the + # function's error; without one, the exec failed before the function + # returned, as when it exited by itself, and its own error is raised. + let raiseFunctionError(err: GraphQLError!): String! { + let reported = ((JSON.decode(err.extensions) :: {{functionError: {{message: String, id: String}}}}).functionError != null) rescue false + if (reported) { + raise err + } + 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) + } + # The module's own source, not the workspace sources reads: that is the # caller's, which holds the module only when the module sits in it. let runtime: Container! { diff --git a/.dagger/modules/e2e/sdk/exe/dagger-mod b/.dagger/modules/e2e/sdk/exe/dagger-mod index 596def3..27d731d 100755 --- a/.dagger/modules/e2e/sdk/exe/dagger-mod +++ b/.dagger/modules/e2e/sdk/exe/dagger-mod @@ -2,21 +2,14 @@ require_relative "../lib/dagger/mod/cli" Dagger.mark_module_runtime! -# A call whose request or signatures no longer match the module's code most -# likely follows an edit made without generation. -calling = ARGV.first == "call" -stale = [Dagger::Mod::InvalidInputError, Dagger::Mod::RegistrationError] +# A call reports its own error, to the engine and in its logs, and returns +# its exit status. +exit Dagger::Mod::CLI.run(ARGV) if ARGV.first == "call" + begin Dagger::Mod::CLI.run(ARGV) rescue Dagger::Mod::Error, Dagger::QueryError => e warn "dagger-mod: #{e.class}: #{e.message}" warn e.stderr if e.is_a?(Dagger::ExecError) && !e.stderr.to_s.empty? - warn "dagger-mod: #{Dagger::Mod::REGENERATE_HINT}" if calling && stale.any? { e.is_a?(it) } exit 2 -rescue LoadError, NameError => e - raise unless calling - - warn e.full_message(highlight: false) - warn "dagger-mod: #{Dagger::Mod::REGENERATE_HINT}" - exit 1 end diff --git a/.dagger/modules/e2e/sdk/lib/dagger/mod.rb b/.dagger/modules/e2e/sdk/lib/dagger/mod.rb index 929fe90..3be88eb 100644 --- a/.dagger/modules/e2e/sdk/lib/dagger/mod.rb +++ b/.dagger/modules/e2e/sdk/lib/dagger/mod.rb @@ -14,5 +14,6 @@ require_relative "mod/module_source" require_relative "mod/convert" require_relative "mod/dispatch" +require_relative "mod/error_report" require_relative "mod/build" require_relative "mod/entrypoint" diff --git a/.dagger/modules/e2e/sdk/lib/dagger/mod/cli.rb b/.dagger/modules/e2e/sdk/lib/dagger/mod/cli.rb index 74e223f..d28bad1 100644 --- a/.dagger/modules/e2e/sdk/lib/dagger/mod/cli.rb +++ b/.dagger/modules/e2e/sdk/lib/dagger/mod/cli.rb @@ -11,13 +11,20 @@ module CLI USAGE = "usage: dagger-mod call|entrypoint|objects [--name ] [--file ] " \ "[--output ] [--client-version ] [--main-object ]".freeze + # What a call whose request or signatures no longer match the module's + # code fails with: most likely an edit made without generation. + STALE = [InvalidInputError, RegistrationError].freeze + module_function + # A call returns its exit status, as it reports its own errors (see + # call); the other commands raise theirs. def run(argv, input: $stdin) command, *rest = argv + return call(rest, input:) if command == "call" + options = parse(rest) case command - when "call" then call(options, input) when "entrypoint" then entrypoint(options) when "objects" then objects(options) else raise Error, USAGE @@ -49,13 +56,29 @@ def entrypoint(options) ::File.write(::File.join(output, "module.rbs"), Entrypoint.render_rbs(Mod.registry)) end - def call(options, input) + # Runs the call, and reports the error it fails with (ErrorReport), + # followed by the hint to run dagger generate after one that most + # likely follows an edit made without it. Returns the exit status: 1 + # when the module doesn't load, 2 for any other error. An exit of the + # function's own, or a signal, ends the process as it would. + def call(argv, input: $stdin, report: ErrorReport.for_module) + loaded = false + options = parse(argv) output = options.fetch(:output) { raise Error, USAGE } request = parse_request(input.read) load_module(options) + loaded = true result = Dispatch.new(Mod.registry).call(request) ::FileUtils.mkdir_p(::File.dirname(output)) ::File.write(output, JSON.generate(result)) + 0 + rescue SystemExit, SignalException + raise + rescue Exception => e # rubocop:disable Lint/RescueException + unloaded = !loaded && (e.is_a?(LoadError) || e.is_a?(NameError)) + stale = unloaded || STALE.any? { e.is_a?(it) } + report.report(e, hint: stale ? "dagger-mod: #{REGENERATE_HINT}" : nil) + unloaded ? 1 : 2 end def parse_request(text) diff --git a/.dagger/modules/e2e/sdk/lib/dagger/mod/dispatch.rb b/.dagger/modules/e2e/sdk/lib/dagger/mod/dispatch.rb index 525027d..465a95c 100644 --- a/.dagger/modules/e2e/sdk/lib/dagger/mod/dispatch.rb +++ b/.dagger/modules/e2e/sdk/lib/dagger/mod/dispatch.rb @@ -4,7 +4,8 @@ module Dagger module Mod # Runs the call a generated entrypoint forwards: the receiver is rebuilt # from its state without initialize, and an empty function name is the - # constructor. + # constructor. What the module's code raises propagates as it is, for the + # call to report (ErrorReport). class Dispatch def initialize(registry) @registry = registry @@ -38,9 +39,9 @@ def construct(klass, args) decl = @registry.constructor(klass) object = if decl - user_code { klass.create(**arguments(decl.args, args, where)) } + klass.create(**arguments(decl.args, args, where)) else - user_code { klass.new(**arguments(@registry.field_args(klass), args, where)) } + klass.new(**arguments(@registry.field_args(klass), args, where)) end @convert.output(object, klass, where) end @@ -53,7 +54,7 @@ def invoke(klass, state, name, args) where = "#{type_name}.#{decl.method_name}" receiver = @convert.restore(klass, state, "#{type_name} state") kwargs = arguments(decl.args, args, where) - value = user_code { receiver.public_send(decl.method_name, **kwargs) } + value = receiver.public_send(decl.method_name, **kwargs) @convert.output(value, decl.returns, "#{where} result") end @@ -69,14 +70,6 @@ def arguments(decls, args, where) end kwargs end - - def user_code - yield - rescue Mod::Error, ::Dagger::QueryError - raise - rescue StandardError => e - raise FunctionError, e.full_message(highlight: false).strip - end end end end diff --git a/.dagger/modules/e2e/sdk/lib/dagger/mod/entrypoint.rb b/.dagger/modules/e2e/sdk/lib/dagger/mod/entrypoint.rb index a0dd6b6..e4bcb06 100644 --- a/.dagger/modules/e2e/sdk/lib/dagger/mod/entrypoint.rb +++ b/.dagger/modules/e2e/sdk/lib/dagger/mod/entrypoint.rb @@ -158,6 +158,13 @@ def indent(lines, width) ModuleTypes().all } + # The module with its gems installed, which every call runs: the engine + # builds it ahead of a call, as the module's build, so a failed install + # shows as the build's, with Bundler's output. + pub prebuild: File! { + runtime.file("Gemfile.lock") + } + pub call( receiverType: String!, receiverValue: JSON, @@ -170,17 +177,49 @@ def indent(lines, width) receiverValue: receiverValue, fnName: fnName, fnArgs: fnArgs, - callDigest: callDigest, moduleSource: currentModule.source.id, }}) - let result = runtime + # A failed install stays out of the rescue below, so it fails the call + # with its own error. An engine that builds prebuild first fails the + # call before it gets here. + let installed = runtime.sync + let result = installed .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + # The exec is cached on its own recipe, which holds neither the + # call's arguments nor its cache policy; the engine's digest of the + # call does (dagger/dagger#14491). It also marks this exec, and no + # other, as the module process, the one that runs the function. + .withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "") .withExec(%s, stdin: request) .file("/dagger/result.json") - .contents + .contents rescue { + err: GraphQLError => raiseFunctionError(err) + } (result :: JSON!) } + # An engine that gives the module process a file for the function's + # error (DAGGER_FUNCTION_ERROR_PATH) puts the error the process wrote + # there in its exec's error, and fails the call with it, values and all: + # the exec's error is raised as it is. Otherwise, as with an older engine + # or a file the process couldn't write, the exec error carries the end + # of the process's stderr, where its last marker line holds the + # function's error; without one, the exec failed before the function + # returned, as when it exited by itself, and its own error is raised. + let raiseFunctionError(err: GraphQLError!): String! { + let reported = ((JSON.decode(err.extensions) :: {{functionError: {{message: String, id: String}}}}).functionError != null) rescue false + if (reported) { + raise err + } + 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) + } + %s} DANG diff --git a/.dagger/modules/e2e/sdk/lib/dagger/mod/error_report.rb b/.dagger/modules/e2e/sdk/lib/dagger/mod/error_report.rb new file mode 100644 index 0000000..f793a3f --- /dev/null +++ b/.dagger/modules/e2e/sdk/lib/dagger/mod/error_report.rb @@ -0,0 +1,250 @@ +require "json" +require "rbconfig" + +module Dagger + module Mod + # Reports the error a module function failed with to the engine. + # + # An engine that names a file for the function's error, in + # DAGGER_FUNCTION_ERROR_PATH, reads the error there and fails the call with + # it, values and all, and shows it: the function's logs then get only a + # short trace, through the module's own frames, in Ruby's own form, and + # nothing for an error the engine shows already, an API error that names + # its origin or one of the SDK's own. Otherwise, as with an older engine + # or a file that can't be written, the error goes to stderr as Ruby prints + # it, followed by one marker line with its message, which the generated + # entrypoint reads. + class ErrorReport + # Starts the line of stderr that carries the function's error for an + # engine that names no file for it. + MARKER = "::dagger-function-error::".freeze + + # Names the file the engine gives a call's process for its function's error. + PATH_ENV = "DAGGER_FUNCTION_ERROR_PATH".freeze + + # The largest function error file the engine reads. + FILE_LIMIT = 1 << 20 + + # What a report over FILE_LIMIT keeps of each long string, before it + # drops the values. + SHORTENED_LENGTH = 64 * 1024 + + # The engine hands the entrypoint the last 100 KiB of a failed exec's + # stderr, and JSON encodes a byte in at most six. + MARKER_LIMIT = 16 * 1024 + + # An origin an error's message names: the span of the call the engine + # reports it from. + ORIGIN = /\s*\[traceparent:[0-9a-f]{32}-[0-9a-f]{16}\]/ + + # The report for the module the process runs, whose code is everything + # but the SDK, the clients generation writes, the installed gems (Gem.path + # holds Bundler's path once bundler/setup ran) and Ruby's own library. A + # path gem the module uses resolves to its own directory, so its frames + # stay. Made before the function runs, which may change the working + # directory. + def self.for_module(module_root: Dir.pwd, sdk_root: File.expand_path("../../..", __dir__.to_s), env: ENV) + roots = [sdk_root, File.join(module_root, "clients"), RbConfig::CONFIG["rubylibprefix"], *Gem.path] + framework = roots.compact.flat_map { [it, real(it)] }.compact.map { "#{it.chomp("/")}/" }.uniq + new(framework:, cwd: module_root, path: env[PATH_ENV]) + end + + def self.real(path) + File.realpath(path) + rescue SystemCallError + nil + end + + # framework: the directories whose code isn't the module's own, each + # ending in /. path: the engine's file for the function's error, if any. + def initialize(framework:, cwd:, path:, stderr: $stderr) + @framework = framework + @cwd = cwd + @path = path.to_s.empty? ? nil : path + @stderr = stderr + end + + # Report error: in the engine's file when there is one and it can be + # written, else with the marker, last. A hint, if any, follows the + # error's own output. + def report(error, hint: nil) + written = write_file(error) + if written + @stderr.write(short_trace(error)) if shows_trace?(error) + else + @stderr.write(full_trace(error)) + end + @stderr.puts(hint) if hint + write_marker(error) unless written + @stderr.flush + end + + # The report the engine reads: {"message": ..., "values": {...}}, the + # error's message in full, with any origin it names, and the extensions + # of the API error it is or was raised from, as they are, such as a + # failed exec's exit code and output. Only a report over what the engine + # reads is shortened: long strings keep their end, where output usually + # says what failed, and the message its start and the origins it names; + # then the values go. + def self.file_report(error) + message = utf8(message_of(error)) + values = utf8(values(error)) + report = encode(message, values) + return report if report.bytesize <= FILE_LIMIT + + message = shorten_message(message, SHORTENED_LENGTH) + report = encode(message, shortened(values)) + return report if report.bytesize <= FILE_LIMIT + + encode(message, {}) + end + + # The error as Ruby prints one it doesn't rescue, causes after it, each + # through the module's own frames only, and without the origins the + # messages name. An error without a frame of the module's, such as a + # file of it that doesn't parse, is its message alone. + def short_trace(error) + self.class.chain(error).map { describe(it) }.join + end + + # Whether the function's logs show the error. The engine shows an API + # error that names its origin with the logs of the call that failed, and + # the message of an error of the SDK's own, which has no frame of the + # module's; an error of the module's own, even one raised from such an + # API error, is the module's to show. + def shows_trace?(error) + return false if error.is_a?(Mod::Error) + + !(error.is_a?(::Dagger::QueryError) && ORIGIN.match?(error.message)) + end + + # The error's message, or its class when it has none: the engine takes + # a report with an empty message for plain text. A SyntaxError's message + # is the file's annotated source, which the function's logs show; its + # first line names the file and the line. + def self.message_of(error) + message = error.message + message = message.lines.first.to_s.chomp if error.is_a?(SyntaxError) + message.strip.empty? ? error.class.name.to_s : message + end + + # The extensions of the first API error in the error's chain of causes. + def self.values(error) + query_error = chain(error).find { it.is_a?(::Dagger::QueryError) } + extensions = query_error.is_a?(::Dagger::QueryError) ? query_error.extensions : nil + extensions.is_a?(Hash) ? extensions : {} + end + + def self.chain(error) + errors = [] #: Array[Exception] + current = error #: Exception? + while current && !errors.include?(current) + errors << current + current = current.cause + end + errors + end + + # The message cut to length bytes, with the origins it names after the cut. + def self.shorten_message(message, length) + return message if message.bytesize <= length + + origins = (message.byteslice(length..) || "").scan(ORIGIN).join + "#{message.byteslice(0, length).to_s.scrub("")}...#{origins}" + end + + # The value with each string longer than SHORTENED_LENGTH, at any depth, + # cut to its end. + def self.shortened(value) + case value + when String + return value if value.bytesize <= SHORTENED_LENGTH + + "...#{value.byteslice(-SHORTENED_LENGTH..).to_s.scrub("")}" + when Hash then value.transform_values { shortened(it) } + when Array then value.map { shortened(it) } + else value + end + end + + def self.utf8(value) + case value + when String then value.dup.force_encoding(Encoding::UTF_8).scrub + when Hash then value.to_h { |key, item| [utf8(key.to_s), utf8(item)] } + when Array then value.map { utf8(it) } + else value + end + end + + def self.encode(message, values) = JSON.generate({ "message" => message, "values" => values }) + + private + + def write_file(error) + path = @path or return false + report = self.class.file_report(error) + File.binwrite(path, report) == report.bytesize + rescue SystemCallError, IOError, JSON::GeneratorError + false + end + + # For an engine that reads no file: the error as Ruby prints it, whole, + # or an API error's or the SDK's message, with a failed exec's stderr, + # as such an engine shows no exec's logs with its error. + def full_trace(error) + return "#{without_origins(error.full_message(highlight: false)).rstrip}\n" unless sdk_error?(error) + + text = "dagger-mod: #{error.class}: #{without_origins(error.message)}\n" + stderr = error.is_a?(::Dagger::ExecError) ? error.stderr.to_s : "" + stderr.empty? ? text : "#{text}#{stderr.chomp}\n" + end + + def write_marker(error) + message = self.class.shorten_message(self.class.utf8(self.class.message_of(error)), MARKER_LIMIT) + @stderr.puts("#{MARKER}#{JSON.generate(message)}") + end + + def sdk_error?(error) = error.is_a?(Mod::Error) || error.is_a?(::Dagger::QueryError) + + # One error of the chain, as Ruby's full_message gives it: the first + # frame, the message and its class, then a line for each other frame. + def describe(error) + frames = module_frames(error) + text = without_origins(detailed_message(error)).rstrip + text = "#{frames.first}: #{text}" unless frames.empty? + "#{text}\n#{frames.drop(1).map { "\tfrom #{it}\n" }.join}" + end + + # Ruby's message and class. SyntaxError's is its own: syntax_suggest's + # guess at the unmatched code reads the file again, and it points at a + # module's first lines as often as at what doesn't parse. + def detailed_message(error) + return error.detailed_message(highlight: false) unless error.is_a?(SyntaxError) + + Exception.instance_method(:detailed_message).bind_call(error, highlight: false) + end + + # A frame's path is its location's, when the frame is still the one + # Ruby recorded, and else the start of its line: a backtrace set since + # need not drop the locations it replaced. + def module_frames(error) + lines = error.backtrace || [] + locations = error.backtrace_locations || [] + lines.each_with_index.filter_map do |line, index| + location = locations[index] + path = location&.to_s == line ? location&.path : line[/\A(.+?):\d+(?::|\z)/, 1] + line if module_file?(path) + end + end + + def module_file?(path) + return false if path.nil? || path.empty? || path.start_with?("<", "(") + + full = File.expand_path(path, @cwd) + @framework.none? { full.start_with?(it) } + end + + def without_origins(text) = text.gsub(ORIGIN, "") + end + end +end diff --git a/.dagger/modules/e2e/sdk/lib/dagger/mod/errors.rb b/.dagger/modules/e2e/sdk/lib/dagger/mod/errors.rb index 92c2dfe..cb6e70d 100644 --- a/.dagger/modules/e2e/sdk/lib/dagger/mod/errors.rb +++ b/.dagger/modules/e2e/sdk/lib/dagger/mod/errors.rb @@ -8,8 +8,6 @@ class InvalidInputError < Error; end class InvalidResultError < Error; end - class FunctionError < Error; end - # What a module most likely needs when it no longer matches its generated # entrypoint, its lock or its clients. REGENERATE_HINT = "if you changed declarations, clients or gems, run `dagger generate`".freeze diff --git a/.dagger/modules/e2e/sdk/sig/mod/mod.rbs b/.dagger/modules/e2e/sdk/sig/mod/mod.rbs index eb578df..726312b 100644 --- a/.dagger/modules/e2e/sdk/sig/mod/mod.rbs +++ b/.dagger/modules/e2e/sdk/sig/mod/mod.rbs @@ -36,9 +36,6 @@ module Dagger class InvalidResultError < Error end - class FunctionError < Error - end - UNSET: ::Object module Naming @@ -388,17 +385,59 @@ module Dagger def construct: (described_class klass, Hash[String, untyped] args) -> untyped def invoke: (described_class klass, Hash[String, untyped] state, String name, Hash[String, untyped] args) -> untyped def arguments: (Array[ArgDecl] decls, Hash[String, untyped] args, String where) -> Hash[Symbol, untyped] - def user_code: [T] () { () -> T } -> T + end + + class ErrorReport + MARKER: String + PATH_ENV: String + FILE_LIMIT: Integer + SHORTENED_LENGTH: Integer + MARKER_LIMIT: Integer + ORIGIN: Regexp + + @framework: Array[String] + @cwd: String + @path: String? + @stderr: IO + + def self.for_module: (?module_root: String, ?sdk_root: String, ?env: untyped) -> ErrorReport + def self.real: (String path) -> String? + def self.file_report: (Exception error) -> String + def self.message_of: (Exception error) -> String + def self.values: (Exception error) -> Hash[String, untyped] + def self.chain: (Exception error) -> Array[Exception] + def self.shorten_message: (String message, Integer length) -> String + def self.shortened: (untyped value) -> untyped + def self.utf8: (untyped value) -> untyped + def self.encode: (String message, Hash[String, untyped] values) -> String + + def initialize: (framework: Array[String], cwd: String, path: String?, ?stderr: IO) -> void + def report: (Exception error, ?hint: String?) -> void + def short_trace: (Exception error) -> String + def shows_trace?: (Exception error) -> bool + + private + + def write_file: (Exception error) -> bool + def full_trace: (Exception error) -> String + def write_marker: (Exception error) -> void + def sdk_error?: (Exception error) -> bool + def describe: (Exception error) -> String + def detailed_message: (Exception error) -> String + def module_frames: (Exception error) -> Array[String] + def module_file?: (String? path) -> bool + def without_origins: (String text) -> String end module CLI USAGE: String + STALE: Array[singleton(Error)] - def self?.run: (Array[String] argv, ?input: IO) -> void + def self?.run: (Array[String] argv, ?input: IO) -> untyped def self?.parse: (Array[String] args) -> Hash[Symbol, String] def self?.entrypoint: (Hash[Symbol, String] options) -> void def self?.objects: (Hash[Symbol, String] options) -> void - def self?.call: (Hash[Symbol, String] options, IO input) -> void + def self?.call: (Array[String] argv, ?input: IO, ?report: ErrorReport) -> Integer def self?.parse_request: (String text) -> Hash[String, untyped] def self?.load_module: (Hash[Symbol, String] options) -> String end diff --git a/AGENTS.md b/AGENTS.md index dc98ef2..9608145 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -129,9 +129,10 @@ A module's `sdk/entrypoint/dang.toml` is the user's despite the marker on `sdk/entrypoint/dang.toml`, which the check does not read. - The entrypoint contract: `types` returns the literal typedefs; `call` runs `dagger-mod call` with the request on stdin and declares a nullable - `callDigest`, which keys its exec. Every module declares `sources`, so its - `types` and `call` take no workspace; a module without gems outside its - directory returns its manifest alone. + `callDigest`, which it sets as `DAGGER_MODULE_CALL_DIGEST` on that exec + alone: it keys the exec, and marks it as the module process. Every module + declares `sources`, so its `types` and `call` take no workspace; a module + without gems outside its directory returns its manifest alone. - Code style: RuboCop's configuration, lines up to 120 characters, comments that say why, not what. In Steep, a literal symbol widens to `Symbol` (annotate `Symbol?`), `grep` does not narrow (use a local and `is_a?`), and diff --git a/CHANGELOG.md b/CHANGELOG.md index b34ecac..a47d187 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,3 +45,9 @@ The first release. It requires Dagger v1.0.0-beta.26 or later. `P11lib`. A class already named after the module by other rules keeps working: the engine takes `HttpServer` for `http-server` and `P11Lib` for `p11lib`. +- A failed function fails its call with its own error: in the engine's + function error file (`DAGGER_FUNCTION_ERROR_PATH`) where the engine gives + one, with the values of the API error it was raised from, and a short trace + of the module's own frames in its logs; on an older engine, with its message. + The entrypoint marks its function's exec with `DAGGER_MODULE_CALL_DIGEST`, + and declares the gems' install as its `prebuild`. diff --git a/README.md b/README.md index 3761746..451a2a2 100644 --- a/README.md +++ b/README.md @@ -562,14 +562,20 @@ again (8 s for a module with one native extension). | `Dagger::ConnectionError` | no session, and none can be started | | `Dagger::ClientLoadError`, `Dagger::StaleClientError` | a client cannot load, or was generated for another core or module | | `Dagger::Mod::RegistrationError` | a declaration or annotation is wrong; raised at generation, naming its file and line | -| `Dagger::Mod::FunctionError` | module code raised | -A function that raises fails its call. A calling module receives an -`ExecError` whose stderr holds the error. +A function that raises fails its call with its own error. On an engine that +gives the module's process a file for it (`DAGGER_FUNCTION_ERROR_PATH`), the +process reports the error there: its message whole, and the values of the API +error it is or was raised from, so a caller of a function that let an +`ExecError` propagate gets an `ExecError` with its exit code and output. The +function's logs then get a short trace in Ruby's own form, through the +module's own frames only, causes included; an API error that names the call +that failed, which the engine shows with that call's logs, logs nothing. +On an older engine the error goes to stderr as Ruby prints it, and the call +fails with its message only. ## What the generated entrypoint cannot do -- Structured errors: a caller sees the failed call and its stderr. - An interface function returning a module object: return an interface instead. ## Known engine limitations diff --git a/hack/designs/ruby-sdk-design.md b/hack/designs/ruby-sdk-design.md index 3eacbe9..37c3b16 100644 --- a/hack/designs/ruby-sdk-design.md +++ b/hack/designs/ruby-sdk-design.md @@ -143,8 +143,11 @@ sequenceDiagram M-->>E: the result as JSON ``` -- The request carries `callDigest`, which keys the exec on the call's whole - identity, its declared clients included (dagger/dagger#14491). +- The exec sets `DAGGER_MODULE_CALL_DIGEST` to `callDigest`, which keys it on + the call's whole identity, its declared clients included + (dagger/dagger#14491), and marks it, and no other exec, as the module + process: the engine serves the module to it and reports its logs on the + function's call. The install, before it, is the module's build. - A function's `cache:` renders `withCachePolicy` in `types.dang`. The engine changes `callDigest` on every call of a `never` function, once per session of a `session` function, and on every evaluation of a function with a time @@ -166,6 +169,33 @@ sequenceDiagram - A failed install prints Bundler's error, then the hint to run `dagger generate`: nothing records whether a module was generated since its last edit, so the hint follows the errors that a missed generation causes. +- The entrypoint declares `prebuild`, a file of the installed container, so + the engine builds the install ahead of the call, under `build `. + +### A failed call + +`dagger-mod call` lets what the module's code raises propagate as it is, and +reports it (`Dagger::Mod::ErrorReport`), then exits 2, so its exec is not +cached; 1 when the module does not load. An `exit` of the function's own ends +the process with its status, and reports nothing. + +- On an engine that sets `DAGGER_FUNCTION_ERROR_PATH`, the report goes to that + file: `{"message", "values"}`, the message whole, its `[traceparent:…]` + origins included, and the extensions of the first API error in the error's + chain of causes, verbatim. The engine fails the call with it. The logs get a + short trace in Ruby's own top-first form, through the module's own frames + only (not the SDK's, the generated clients', the gems' or Ruby's), causes + after, without origins; an error with no frame of the module's, such as a + file that doesn't parse, is its message and class alone. An API error that + names its origin, and an error of the SDK's own, log nothing: the engine + shows them. A SyntaxError's message is its annotated source, so its report + is its first line, which names the file and the line, and its trace leaves + out syntax_suggest's guess, which reads the file again. +- Otherwise, the error goes to stderr as Ruby prints it, then a last line, + `::dagger-function-error::` and the message as a JSON string, cut to 16 KiB, + which `call` in `main.dang` raises. `call` raises the exec's error as it is + when the engine put the report in it (`functionError`), or when there is no + marker line, as after an `exit`. ## The entrypoint contract diff --git a/sdk/exe/dagger-mod b/sdk/exe/dagger-mod index 596def3..27d731d 100755 --- a/sdk/exe/dagger-mod +++ b/sdk/exe/dagger-mod @@ -2,21 +2,14 @@ require_relative "../lib/dagger/mod/cli" Dagger.mark_module_runtime! -# A call whose request or signatures no longer match the module's code most -# likely follows an edit made without generation. -calling = ARGV.first == "call" -stale = [Dagger::Mod::InvalidInputError, Dagger::Mod::RegistrationError] +# A call reports its own error, to the engine and in its logs, and returns +# its exit status. +exit Dagger::Mod::CLI.run(ARGV) if ARGV.first == "call" + begin Dagger::Mod::CLI.run(ARGV) rescue Dagger::Mod::Error, Dagger::QueryError => e warn "dagger-mod: #{e.class}: #{e.message}" warn e.stderr if e.is_a?(Dagger::ExecError) && !e.stderr.to_s.empty? - warn "dagger-mod: #{Dagger::Mod::REGENERATE_HINT}" if calling && stale.any? { e.is_a?(it) } exit 2 -rescue LoadError, NameError => e - raise unless calling - - warn e.full_message(highlight: false) - warn "dagger-mod: #{Dagger::Mod::REGENERATE_HINT}" - exit 1 end diff --git a/sdk/lib/dagger/mod.rb b/sdk/lib/dagger/mod.rb index 929fe90..3be88eb 100644 --- a/sdk/lib/dagger/mod.rb +++ b/sdk/lib/dagger/mod.rb @@ -14,5 +14,6 @@ require_relative "mod/module_source" require_relative "mod/convert" require_relative "mod/dispatch" +require_relative "mod/error_report" require_relative "mod/build" require_relative "mod/entrypoint" diff --git a/sdk/lib/dagger/mod/cli.rb b/sdk/lib/dagger/mod/cli.rb index 74e223f..d28bad1 100644 --- a/sdk/lib/dagger/mod/cli.rb +++ b/sdk/lib/dagger/mod/cli.rb @@ -11,13 +11,20 @@ module CLI USAGE = "usage: dagger-mod call|entrypoint|objects [--name ] [--file ] " \ "[--output ] [--client-version ] [--main-object ]".freeze + # What a call whose request or signatures no longer match the module's + # code fails with: most likely an edit made without generation. + STALE = [InvalidInputError, RegistrationError].freeze + module_function + # A call returns its exit status, as it reports its own errors (see + # call); the other commands raise theirs. def run(argv, input: $stdin) command, *rest = argv + return call(rest, input:) if command == "call" + options = parse(rest) case command - when "call" then call(options, input) when "entrypoint" then entrypoint(options) when "objects" then objects(options) else raise Error, USAGE @@ -49,13 +56,29 @@ def entrypoint(options) ::File.write(::File.join(output, "module.rbs"), Entrypoint.render_rbs(Mod.registry)) end - def call(options, input) + # Runs the call, and reports the error it fails with (ErrorReport), + # followed by the hint to run dagger generate after one that most + # likely follows an edit made without it. Returns the exit status: 1 + # when the module doesn't load, 2 for any other error. An exit of the + # function's own, or a signal, ends the process as it would. + def call(argv, input: $stdin, report: ErrorReport.for_module) + loaded = false + options = parse(argv) output = options.fetch(:output) { raise Error, USAGE } request = parse_request(input.read) load_module(options) + loaded = true result = Dispatch.new(Mod.registry).call(request) ::FileUtils.mkdir_p(::File.dirname(output)) ::File.write(output, JSON.generate(result)) + 0 + rescue SystemExit, SignalException + raise + rescue Exception => e # rubocop:disable Lint/RescueException + unloaded = !loaded && (e.is_a?(LoadError) || e.is_a?(NameError)) + stale = unloaded || STALE.any? { e.is_a?(it) } + report.report(e, hint: stale ? "dagger-mod: #{REGENERATE_HINT}" : nil) + unloaded ? 1 : 2 end def parse_request(text) diff --git a/sdk/lib/dagger/mod/dispatch.rb b/sdk/lib/dagger/mod/dispatch.rb index 525027d..465a95c 100644 --- a/sdk/lib/dagger/mod/dispatch.rb +++ b/sdk/lib/dagger/mod/dispatch.rb @@ -4,7 +4,8 @@ module Dagger module Mod # Runs the call a generated entrypoint forwards: the receiver is rebuilt # from its state without initialize, and an empty function name is the - # constructor. + # constructor. What the module's code raises propagates as it is, for the + # call to report (ErrorReport). class Dispatch def initialize(registry) @registry = registry @@ -38,9 +39,9 @@ def construct(klass, args) decl = @registry.constructor(klass) object = if decl - user_code { klass.create(**arguments(decl.args, args, where)) } + klass.create(**arguments(decl.args, args, where)) else - user_code { klass.new(**arguments(@registry.field_args(klass), args, where)) } + klass.new(**arguments(@registry.field_args(klass), args, where)) end @convert.output(object, klass, where) end @@ -53,7 +54,7 @@ def invoke(klass, state, name, args) where = "#{type_name}.#{decl.method_name}" receiver = @convert.restore(klass, state, "#{type_name} state") kwargs = arguments(decl.args, args, where) - value = user_code { receiver.public_send(decl.method_name, **kwargs) } + value = receiver.public_send(decl.method_name, **kwargs) @convert.output(value, decl.returns, "#{where} result") end @@ -69,14 +70,6 @@ def arguments(decls, args, where) end kwargs end - - def user_code - yield - rescue Mod::Error, ::Dagger::QueryError - raise - rescue StandardError => e - raise FunctionError, e.full_message(highlight: false).strip - end end end end diff --git a/sdk/lib/dagger/mod/entrypoint.rb b/sdk/lib/dagger/mod/entrypoint.rb index a0dd6b6..e4bcb06 100644 --- a/sdk/lib/dagger/mod/entrypoint.rb +++ b/sdk/lib/dagger/mod/entrypoint.rb @@ -158,6 +158,13 @@ def indent(lines, width) ModuleTypes().all } + # The module with its gems installed, which every call runs: the engine + # builds it ahead of a call, as the module's build, so a failed install + # shows as the build's, with Bundler's output. + pub prebuild: File! { + runtime.file("Gemfile.lock") + } + pub call( receiverType: String!, receiverValue: JSON, @@ -170,17 +177,49 @@ def indent(lines, width) receiverValue: receiverValue, fnName: fnName, fnArgs: fnArgs, - callDigest: callDigest, moduleSource: currentModule.source.id, }}) - let result = runtime + # A failed install stays out of the rescue below, so it fails the call + # with its own error. An engine that builds prebuild first fails the + # call before it gets here. + let installed = runtime.sync + let result = installed .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + # The exec is cached on its own recipe, which holds neither the + # call's arguments nor its cache policy; the engine's digest of the + # call does (dagger/dagger#14491). It also marks this exec, and no + # other, as the module process, the one that runs the function. + .withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "") .withExec(%s, stdin: request) .file("/dagger/result.json") - .contents + .contents rescue { + err: GraphQLError => raiseFunctionError(err) + } (result :: JSON!) } + # An engine that gives the module process a file for the function's + # error (DAGGER_FUNCTION_ERROR_PATH) puts the error the process wrote + # there in its exec's error, and fails the call with it, values and all: + # the exec's error is raised as it is. Otherwise, as with an older engine + # or a file the process couldn't write, the exec error carries the end + # of the process's stderr, where its last marker line holds the + # function's error; without one, the exec failed before the function + # returned, as when it exited by itself, and its own error is raised. + let raiseFunctionError(err: GraphQLError!): String! { + let reported = ((JSON.decode(err.extensions) :: {{functionError: {{message: String, id: String}}}}).functionError != null) rescue false + if (reported) { + raise err + } + 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) + } + %s} DANG diff --git a/sdk/lib/dagger/mod/error_report.rb b/sdk/lib/dagger/mod/error_report.rb new file mode 100644 index 0000000..f793a3f --- /dev/null +++ b/sdk/lib/dagger/mod/error_report.rb @@ -0,0 +1,250 @@ +require "json" +require "rbconfig" + +module Dagger + module Mod + # Reports the error a module function failed with to the engine. + # + # An engine that names a file for the function's error, in + # DAGGER_FUNCTION_ERROR_PATH, reads the error there and fails the call with + # it, values and all, and shows it: the function's logs then get only a + # short trace, through the module's own frames, in Ruby's own form, and + # nothing for an error the engine shows already, an API error that names + # its origin or one of the SDK's own. Otherwise, as with an older engine + # or a file that can't be written, the error goes to stderr as Ruby prints + # it, followed by one marker line with its message, which the generated + # entrypoint reads. + class ErrorReport + # Starts the line of stderr that carries the function's error for an + # engine that names no file for it. + MARKER = "::dagger-function-error::".freeze + + # Names the file the engine gives a call's process for its function's error. + PATH_ENV = "DAGGER_FUNCTION_ERROR_PATH".freeze + + # The largest function error file the engine reads. + FILE_LIMIT = 1 << 20 + + # What a report over FILE_LIMIT keeps of each long string, before it + # drops the values. + SHORTENED_LENGTH = 64 * 1024 + + # The engine hands the entrypoint the last 100 KiB of a failed exec's + # stderr, and JSON encodes a byte in at most six. + MARKER_LIMIT = 16 * 1024 + + # An origin an error's message names: the span of the call the engine + # reports it from. + ORIGIN = /\s*\[traceparent:[0-9a-f]{32}-[0-9a-f]{16}\]/ + + # The report for the module the process runs, whose code is everything + # but the SDK, the clients generation writes, the installed gems (Gem.path + # holds Bundler's path once bundler/setup ran) and Ruby's own library. A + # path gem the module uses resolves to its own directory, so its frames + # stay. Made before the function runs, which may change the working + # directory. + def self.for_module(module_root: Dir.pwd, sdk_root: File.expand_path("../../..", __dir__.to_s), env: ENV) + roots = [sdk_root, File.join(module_root, "clients"), RbConfig::CONFIG["rubylibprefix"], *Gem.path] + framework = roots.compact.flat_map { [it, real(it)] }.compact.map { "#{it.chomp("/")}/" }.uniq + new(framework:, cwd: module_root, path: env[PATH_ENV]) + end + + def self.real(path) + File.realpath(path) + rescue SystemCallError + nil + end + + # framework: the directories whose code isn't the module's own, each + # ending in /. path: the engine's file for the function's error, if any. + def initialize(framework:, cwd:, path:, stderr: $stderr) + @framework = framework + @cwd = cwd + @path = path.to_s.empty? ? nil : path + @stderr = stderr + end + + # Report error: in the engine's file when there is one and it can be + # written, else with the marker, last. A hint, if any, follows the + # error's own output. + def report(error, hint: nil) + written = write_file(error) + if written + @stderr.write(short_trace(error)) if shows_trace?(error) + else + @stderr.write(full_trace(error)) + end + @stderr.puts(hint) if hint + write_marker(error) unless written + @stderr.flush + end + + # The report the engine reads: {"message": ..., "values": {...}}, the + # error's message in full, with any origin it names, and the extensions + # of the API error it is or was raised from, as they are, such as a + # failed exec's exit code and output. Only a report over what the engine + # reads is shortened: long strings keep their end, where output usually + # says what failed, and the message its start and the origins it names; + # then the values go. + def self.file_report(error) + message = utf8(message_of(error)) + values = utf8(values(error)) + report = encode(message, values) + return report if report.bytesize <= FILE_LIMIT + + message = shorten_message(message, SHORTENED_LENGTH) + report = encode(message, shortened(values)) + return report if report.bytesize <= FILE_LIMIT + + encode(message, {}) + end + + # The error as Ruby prints one it doesn't rescue, causes after it, each + # through the module's own frames only, and without the origins the + # messages name. An error without a frame of the module's, such as a + # file of it that doesn't parse, is its message alone. + def short_trace(error) + self.class.chain(error).map { describe(it) }.join + end + + # Whether the function's logs show the error. The engine shows an API + # error that names its origin with the logs of the call that failed, and + # the message of an error of the SDK's own, which has no frame of the + # module's; an error of the module's own, even one raised from such an + # API error, is the module's to show. + def shows_trace?(error) + return false if error.is_a?(Mod::Error) + + !(error.is_a?(::Dagger::QueryError) && ORIGIN.match?(error.message)) + end + + # The error's message, or its class when it has none: the engine takes + # a report with an empty message for plain text. A SyntaxError's message + # is the file's annotated source, which the function's logs show; its + # first line names the file and the line. + def self.message_of(error) + message = error.message + message = message.lines.first.to_s.chomp if error.is_a?(SyntaxError) + message.strip.empty? ? error.class.name.to_s : message + end + + # The extensions of the first API error in the error's chain of causes. + def self.values(error) + query_error = chain(error).find { it.is_a?(::Dagger::QueryError) } + extensions = query_error.is_a?(::Dagger::QueryError) ? query_error.extensions : nil + extensions.is_a?(Hash) ? extensions : {} + end + + def self.chain(error) + errors = [] #: Array[Exception] + current = error #: Exception? + while current && !errors.include?(current) + errors << current + current = current.cause + end + errors + end + + # The message cut to length bytes, with the origins it names after the cut. + def self.shorten_message(message, length) + return message if message.bytesize <= length + + origins = (message.byteslice(length..) || "").scan(ORIGIN).join + "#{message.byteslice(0, length).to_s.scrub("")}...#{origins}" + end + + # The value with each string longer than SHORTENED_LENGTH, at any depth, + # cut to its end. + def self.shortened(value) + case value + when String + return value if value.bytesize <= SHORTENED_LENGTH + + "...#{value.byteslice(-SHORTENED_LENGTH..).to_s.scrub("")}" + when Hash then value.transform_values { shortened(it) } + when Array then value.map { shortened(it) } + else value + end + end + + def self.utf8(value) + case value + when String then value.dup.force_encoding(Encoding::UTF_8).scrub + when Hash then value.to_h { |key, item| [utf8(key.to_s), utf8(item)] } + when Array then value.map { utf8(it) } + else value + end + end + + def self.encode(message, values) = JSON.generate({ "message" => message, "values" => values }) + + private + + def write_file(error) + path = @path or return false + report = self.class.file_report(error) + File.binwrite(path, report) == report.bytesize + rescue SystemCallError, IOError, JSON::GeneratorError + false + end + + # For an engine that reads no file: the error as Ruby prints it, whole, + # or an API error's or the SDK's message, with a failed exec's stderr, + # as such an engine shows no exec's logs with its error. + def full_trace(error) + return "#{without_origins(error.full_message(highlight: false)).rstrip}\n" unless sdk_error?(error) + + text = "dagger-mod: #{error.class}: #{without_origins(error.message)}\n" + stderr = error.is_a?(::Dagger::ExecError) ? error.stderr.to_s : "" + stderr.empty? ? text : "#{text}#{stderr.chomp}\n" + end + + def write_marker(error) + message = self.class.shorten_message(self.class.utf8(self.class.message_of(error)), MARKER_LIMIT) + @stderr.puts("#{MARKER}#{JSON.generate(message)}") + end + + def sdk_error?(error) = error.is_a?(Mod::Error) || error.is_a?(::Dagger::QueryError) + + # One error of the chain, as Ruby's full_message gives it: the first + # frame, the message and its class, then a line for each other frame. + def describe(error) + frames = module_frames(error) + text = without_origins(detailed_message(error)).rstrip + text = "#{frames.first}: #{text}" unless frames.empty? + "#{text}\n#{frames.drop(1).map { "\tfrom #{it}\n" }.join}" + end + + # Ruby's message and class. SyntaxError's is its own: syntax_suggest's + # guess at the unmatched code reads the file again, and it points at a + # module's first lines as often as at what doesn't parse. + def detailed_message(error) + return error.detailed_message(highlight: false) unless error.is_a?(SyntaxError) + + Exception.instance_method(:detailed_message).bind_call(error, highlight: false) + end + + # A frame's path is its location's, when the frame is still the one + # Ruby recorded, and else the start of its line: a backtrace set since + # need not drop the locations it replaced. + def module_frames(error) + lines = error.backtrace || [] + locations = error.backtrace_locations || [] + lines.each_with_index.filter_map do |line, index| + location = locations[index] + path = location&.to_s == line ? location&.path : line[/\A(.+?):\d+(?::|\z)/, 1] + line if module_file?(path) + end + end + + def module_file?(path) + return false if path.nil? || path.empty? || path.start_with?("<", "(") + + full = File.expand_path(path, @cwd) + @framework.none? { full.start_with?(it) } + end + + def without_origins(text) = text.gsub(ORIGIN, "") + end + end +end diff --git a/sdk/lib/dagger/mod/errors.rb b/sdk/lib/dagger/mod/errors.rb index 92c2dfe..cb6e70d 100644 --- a/sdk/lib/dagger/mod/errors.rb +++ b/sdk/lib/dagger/mod/errors.rb @@ -8,8 +8,6 @@ class InvalidInputError < Error; end class InvalidResultError < Error; end - class FunctionError < Error; end - # What a module most likely needs when it no longer matches its generated # entrypoint, its lock or its clients. REGENERATE_HINT = "if you changed declarations, clients or gems, run `dagger generate`".freeze diff --git a/sdk/sig/mod/mod.rbs b/sdk/sig/mod/mod.rbs index eb578df..726312b 100644 --- a/sdk/sig/mod/mod.rbs +++ b/sdk/sig/mod/mod.rbs @@ -36,9 +36,6 @@ module Dagger class InvalidResultError < Error end - class FunctionError < Error - end - UNSET: ::Object module Naming @@ -388,17 +385,59 @@ module Dagger def construct: (described_class klass, Hash[String, untyped] args) -> untyped def invoke: (described_class klass, Hash[String, untyped] state, String name, Hash[String, untyped] args) -> untyped def arguments: (Array[ArgDecl] decls, Hash[String, untyped] args, String where) -> Hash[Symbol, untyped] - def user_code: [T] () { () -> T } -> T + end + + class ErrorReport + MARKER: String + PATH_ENV: String + FILE_LIMIT: Integer + SHORTENED_LENGTH: Integer + MARKER_LIMIT: Integer + ORIGIN: Regexp + + @framework: Array[String] + @cwd: String + @path: String? + @stderr: IO + + def self.for_module: (?module_root: String, ?sdk_root: String, ?env: untyped) -> ErrorReport + def self.real: (String path) -> String? + def self.file_report: (Exception error) -> String + def self.message_of: (Exception error) -> String + def self.values: (Exception error) -> Hash[String, untyped] + def self.chain: (Exception error) -> Array[Exception] + def self.shorten_message: (String message, Integer length) -> String + def self.shortened: (untyped value) -> untyped + def self.utf8: (untyped value) -> untyped + def self.encode: (String message, Hash[String, untyped] values) -> String + + def initialize: (framework: Array[String], cwd: String, path: String?, ?stderr: IO) -> void + def report: (Exception error, ?hint: String?) -> void + def short_trace: (Exception error) -> String + def shows_trace?: (Exception error) -> bool + + private + + def write_file: (Exception error) -> bool + def full_trace: (Exception error) -> String + def write_marker: (Exception error) -> void + def sdk_error?: (Exception error) -> bool + def describe: (Exception error) -> String + def detailed_message: (Exception error) -> String + def module_frames: (Exception error) -> Array[String] + def module_file?: (String? path) -> bool + def without_origins: (String text) -> String end module CLI USAGE: String + STALE: Array[singleton(Error)] - def self?.run: (Array[String] argv, ?input: IO) -> void + def self?.run: (Array[String] argv, ?input: IO) -> untyped def self?.parse: (Array[String] args) -> Hash[Symbol, String] def self?.entrypoint: (Hash[Symbol, String] options) -> void def self?.objects: (Hash[Symbol, String] options) -> void - def self?.call: (Hash[Symbol, String] options, IO input) -> void + def self?.call: (Array[String] argv, ?input: IO, ?report: ErrorReport) -> Integer def self?.parse_request: (String text) -> Hash[String, untyped] def self?.load_module: (Hash[Symbol, String] options) -> String end diff --git a/test/golden/mod/main-sources.dang b/test/golden/mod/main-sources.dang index 9e1a281..6eedbf8 100644 --- a/test/golden/mod/main-sources.dang +++ b/test/golden/mod/main-sources.dang @@ -23,6 +23,13 @@ type Entrypoint implements ModuleEntrypoint { ModuleTypes().all } + # The module with its gems installed, which every call runs: the engine + # builds it ahead of a call, as the module's build, so a failed install + # shows as the build's, with Bundler's output. + pub prebuild: File! { + runtime.file("Gemfile.lock") + } + pub call( receiverType: String!, receiverValue: JSON, @@ -35,17 +42,49 @@ type Entrypoint implements ModuleEntrypoint { receiverValue: receiverValue, fnName: fnName, fnArgs: fnArgs, - callDigest: callDigest, moduleSource: currentModule.source.id, }}) - let result = runtime + # A failed install stays out of the rescue below, so it fails the call + # with its own error. An engine that builds prebuild first fails the + # call before it gets here. + let installed = runtime.sync + let result = installed .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + # The exec is cached on its own recipe, which holds neither the + # call's arguments nor its cache policy; the engine's digest of the + # call does (dagger/dagger#14491). It also marks this exec, and no + # other, as the module process, the one that runs the function. + .withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "") .withExec(["ruby", "-rbundler/setup", "sdk/exe/dagger-mod", "call", "--output", "/dagger/result.json"], stdin: request) .file("/dagger/result.json") - .contents + .contents rescue { + err: GraphQLError => raiseFunctionError(err) + } (result :: JSON!) } + # An engine that gives the module process a file for the function's + # error (DAGGER_FUNCTION_ERROR_PATH) puts the error the process wrote + # there in its exec's error, and fails the call with it, values and all: + # the exec's error is raised as it is. Otherwise, as with an older engine + # or a file the process couldn't write, the exec error carries the end + # of the process's stderr, where its last marker line holds the + # function's error; without one, the exec failed before the function + # returned, as when it exited by itself, and its own error is raised. + let raiseFunctionError(err: GraphQLError!): String! { + let reported = ((JSON.decode(err.extensions) :: {{functionError: {{message: String, id: String}}}}).functionError != null) rescue false + if (reported) { + raise err + } + 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) + } + # The module's context directory, with the module's own source at its # subpath, beside what sources returns. let runtime: Container! { diff --git a/test/golden/mod/main.dang b/test/golden/mod/main.dang index 77b85e7..56f8088 100644 --- a/test/golden/mod/main.dang +++ b/test/golden/mod/main.dang @@ -21,6 +21,13 @@ type Entrypoint implements ModuleEntrypoint { ModuleTypes().all } + # The module with its gems installed, which every call runs: the engine + # builds it ahead of a call, as the module's build, so a failed install + # shows as the build's, with Bundler's output. + pub prebuild: File! { + runtime.file("Gemfile.lock") + } + pub call( receiverType: String!, receiverValue: JSON, @@ -33,17 +40,49 @@ type Entrypoint implements ModuleEntrypoint { receiverValue: receiverValue, fnName: fnName, fnArgs: fnArgs, - callDigest: callDigest, moduleSource: currentModule.source.id, }}) - let result = runtime + # A failed install stays out of the rescue below, so it fails the call + # with its own error. An engine that builds prebuild first fails the + # call before it gets here. + let installed = runtime.sync + let result = installed .withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion) + # The exec is cached on its own recipe, which holds neither the + # call's arguments nor its cache policy; the engine's digest of the + # call does (dagger/dagger#14491). It also marks this exec, and no + # other, as the module process, the one that runs the function. + .withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "") .withExec(["ruby", "-rbundler/setup", "sdk/exe/dagger-mod", "call", "--output", "/dagger/result.json"], stdin: request) .file("/dagger/result.json") - .contents + .contents rescue { + err: GraphQLError => raiseFunctionError(err) + } (result :: JSON!) } + # An engine that gives the module process a file for the function's + # error (DAGGER_FUNCTION_ERROR_PATH) puts the error the process wrote + # there in its exec's error, and fails the call with it, values and all: + # the exec's error is raised as it is. Otherwise, as with an older engine + # or a file the process couldn't write, the exec error carries the end + # of the process's stderr, where its last marker line holds the + # function's error; without one, the exec failed before the function + # returned, as when it exited by itself, and its own error is raised. + let raiseFunctionError(err: GraphQLError!): String! { + let reported = ((JSON.decode(err.extensions) :: {{functionError: {{message: String, id: String}}}}).functionError != null) rescue false + if (reported) { + raise err + } + 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) + } + # The module's own source, not the workspace sources reads: that is the # caller's, which holds the module only when the module sits in it. let runtime: Container! { diff --git a/test/mod/dispatch_test.rb b/test/mod/dispatch_test.rb index d2cd488..cc72ad9 100644 --- a/test/mod/dispatch_test.rb +++ b/test/mod/dispatch_test.rb @@ -63,6 +63,10 @@ def stamp(stamp: "\#{greeting}!") = stamp #: () -> void def fail = raise(ArgumentError, "boom") + function + #: () -> void + def quit = exit(3) + function #: () -> String def wrong = 42 @@ -160,7 +164,7 @@ def test_a_core_object_arrives_by_id_and_is_loaded_with_node end def test_errors - assert_raises(Dagger::Mod::FunctionError) { dispatch("fail", receiver: state) } + assert_raises(ArgumentError) { dispatch("fail", receiver: state) } assert_raises(Dagger::Mod::InvalidResultError) { dispatch("wrong", receiver: state) } assert_raises(Dagger::Mod::InvalidInputError) { dispatch("greet", receiver: state, mood: "SAD") } assert_raises(Dagger::Mod::InvalidInputError) { dispatch("nope", receiver: state) } @@ -175,11 +179,42 @@ def test_the_cli_writes_a_result_or_exits_2_without_one assert_equal [0, '"hi, cli (happy)"'], [ok_status.exitstatus, File.read(File.join(dir, "ok.json"))], ok assert_equal 2, failed_status.exitstatus - assert_match(/FunctionError: .*boom/, failed) + assert_match(/main\.rb:\d+:in 'Main#fail': boom \(ArgumentError\)\n/, failed) + assert_includes failed, "dagger/mod/cli.rb" + assert failed.end_with?(%(::dagger-function-error::"boom"\n)), failed refute_path_exists File.join(dir, "fail.json") end end + # An engine that names a file for the function's error reads it there, and + # the function's logs get the module's own frames only. + def test_the_cli_reports_a_failed_call_in_the_engines_file + Dir.mktmpdir do |dir| + write_module(dir) + report = File.join(dir, "error.json") + failed, failed_status = run_cli(dir, "fail", "{}", env: { Dagger::Mod::ErrorReport::PATH_ENV => report }) + + assert_equal 2, failed_status.exitstatus + assert_equal({ "message" => "boom", "values" => {} }, JSON.parse(File.read(report))) + # Ruby's error_highlight may point at the call that raised. + assert_match(/\A\S*main\.rb:\d+:in 'Main#fail': boom \(ArgumentError\)\n/, failed) + refute_match(/dispatch\.rb|cli\.rb|dagger-mod|from /, failed) + end + end + + # An exit of the function's own ends the process with its status, and + # reports nothing: the engine fails the call with the exec's error. + def test_a_function_that_exits_keeps_its_status + Dir.mktmpdir do |dir| + write_module(dir) + report = File.join(dir, "error.json") + out, status = run_cli(dir, "quit", "{}", env: { Dagger::Mod::ErrorReport::PATH_ENV => report }) + + assert_equal [3, ""], [status.exitstatus, out] + refute_path_exists report + end + end + def test_a_call_the_module_no_longer_matches_shows_its_error_and_the_hint Dir.mktmpdir do |dir| write_module(dir) @@ -236,12 +271,12 @@ def write_module(dir) JSON.generate(RubySdk::Signatures.parse("main.rb" => source))) end - def run_cli(dir, fn_name, args) + def run_cli(dir, fn_name, args, env: {}) request = JSON.generate("receiverType" => "Main", "receiverValue" => JSON.generate(state), "fnName" => fn_name, "fnArgs" => args) output = File.join(dir, fn_name == "fail" ? "fail.json" : "ok.json") sdk = File.expand_path("../../sdk", __dir__) - Open3.capture2e({ "DAGGER_MODULE" => "main", "DAGGER_MODULE_FILE" => "main.rb" }, + Open3.capture2e({ "DAGGER_MODULE" => "main", "DAGGER_MODULE_FILE" => "main.rb", **env }, "ruby", "-I", "#{sdk}/lib", "#{sdk}/exe/dagger-mod", "call", "--output", output, stdin_data: request, chdir: dir) end diff --git a/test/mod/entrypoint_test.rb b/test/mod/entrypoint_test.rb index d080809..48fe3bd 100644 --- a/test/mod/entrypoint_test.rb +++ b/test/mod/entrypoint_test.rb @@ -80,7 +80,8 @@ def test_the_call_sets_the_client_version_before_it_runs_the_module [Entrypoint.render_main("main", client_version: "v9"), Entrypoint.render_main("main", client_version: "v9", outside: ["../shared"])].each do |main| assert_includes main, %( let clientVersion: String! = "v9"\n) - assert_match(/\.withEnvVariable\("DAGGER_CLIENT_VERSION", clientVersion\)\n\s*\.withExec\(\["ruby"/, main) + version = /\.withEnvVariable\("DAGGER_CLIENT_VERSION", clientVersion\)\n/ + assert_match(/#{version}(?:\s*(?:#|\.withEnvVariable).*\n)*\s*\.withExec\(\["ruby"/, main) end end @@ -90,12 +91,37 @@ def test_the_entrypoint_command_requires_the_client_version assert_includes error.message, "--client-version" end - def test_the_call_declares_the_call_digest_and_sends_it + # The digest keys the exec on the call, and marks it, and no other exec, + # as the module process: the install before it is the module's build. + def test_the_call_declares_the_call_digest_and_marks_its_exec_with_it main = Entrypoint.render_main("main", client_version: CLIENT_VERSION) + install = main.index("let installed = runtime.sync") + marked = main.index('.withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "")') + exec = main.index('.withExec(["ruby", "-rbundler/setup", "sdk/exe/dagger-mod", "call", "--output", ' \ + '"/dagger/result.json"], stdin: request)') assert_includes main, " callDigest: String,\n ): JSON! {" - assert_includes main, " callDigest: callDigest,\n" - assert_includes main, '.withExec(["ruby", "-rbundler/setup", "sdk/exe/dagger-mod", "call", "--output", ' \ - '"/dagger/result.json"], stdin: request)' + assert_equal 1, main.scan("DAGGER_MODULE_CALL_DIGEST").size + assert_operator install, :<, marked + assert_operator marked, :<, exec + end + + # The engine builds prebuild ahead of a call, as the module's build: the + # module's container, its gems installed. + def test_the_entrypoint_declares_the_install_as_its_prebuild + main = Entrypoint.render_main("main", client_version: CLIENT_VERSION) + + assert_includes main, " pub prebuild: File! {\n runtime.file(\"Gemfile.lock\")\n }\n" + end + + # The exec's error is raised as it is when the engine read the function's + # error from its file; otherwise the dispatcher's last marker line has it. + def test_the_call_raises_the_function_error + main = Entrypoint.render_main("main", client_version: CLIENT_VERSION) + + assert_includes main, ".contents rescue {\n err: GraphQLError => raiseFunctionError(err)\n }" + assert_includes main, "functionError: {{message: String, id: String}}" + assert_includes main, %(let marker = "#{Dagger::Mod::ErrorReport::MARKER}") + assert_includes main, 'stderr.split("\n")' end end diff --git a/test/mod/error_report_test.rb b/test/mod/error_report_test.rb new file mode 100644 index 0000000..0cd2f49 --- /dev/null +++ b/test/mod/error_report_test.rb @@ -0,0 +1,188 @@ +require_relative "mod_helper" +require "stringio" +require "tmpdir" + +class ErrorReportTest < Minitest::Test + ORIGIN = "[traceparent:#{"a" * 32}-#{"b" * 16}]".freeze + SDK_FRAMES = ["/src/sdk/lib/dagger/mod/dispatch.rb:56:in 'Kernel#public_send'", + "sdk/exe/dagger-mod:7:in '
'"].freeze + EXTENSIONS = { "_type" => "EXEC_ERROR", "cmd" => %w[sh -c false], "exitCode" => 1, "stdout" => "out", + "stderr" => "oops" }.freeze + FRAMEWORK = ["/src/sdk/", "/src/clients/", "/usr/local/bundle/", "/usr/local/lib/ruby/"].freeze + + def test_an_error_of_the_module_goes_to_the_file_and_its_logs_get_its_own_frames + error = raised(RuntimeError.new("boom"), "/src/lib/main.rb:3:in 'Main#fail'", *SDK_FRAMES, + "/usr/local/bundle/gems/x-1/lib/x.rb:1:in 'X.y'", "/src/lib/main/helper.rb:9:in 'Helper.go'") + file, logs = report_to_file(error) + + assert_equal({ "message" => "boom", "values" => {} }, JSON.parse(file)) + assert_equal "/src/lib/main.rb:3:in 'Main#fail': boom (RuntimeError)\n" \ + "\tfrom /src/lib/main/helper.rb:9:in 'Helper.go'\n", logs + end + + # The engine shows an API error that names its origin with the logs of the + # call that failed; the report keeps the origin and the error's values. + def test_an_api_error_that_names_its_origin_logs_nothing + file, logs = report_to_file(raised(exec_error, "/src/sdk/lib/dagger/connection.rb:87:in 'read'", + "/src/lib/main.rb:5:in 'Main#run'")) + + assert_equal({ "message" => "exit code: 1 #{ORIGIN}", "values" => EXTENSIONS }, JSON.parse(file)) + assert_empty logs + end + + # Ruby makes the error being rescued the cause of one raised in its rescue. + def test_a_wrapped_api_error_logs_both_without_origins_and_reports_the_api_errors_values + error = wrap(exec_error) { raise "ran a failing command: #{it.message}" } + file, logs = report_to_file(error) + report = JSON.parse(file) + + assert_equal "ran a failing command: exit code: 1 #{ORIGIN}", report["message"] + assert_equal EXTENSIONS, report["values"] + assert_match(/\A\S+error_report_test\.rb:\d+:in .*: ran a failing command: exit code: 1 \(RuntimeError\)\n/, logs) + assert_match(/^\S+error_report_test\.rb:\d+:in .*: exit code: 1 \(Dagger::ExecError\)\n/, logs) + refute_includes logs, "traceparent" + end + + def test_an_error_of_the_sdk_logs_only_the_hint + file, logs = report_to_file(raised(Dagger::Mod::InvalidInputError.new("Main has no function nope"), *SDK_FRAMES), + hint: "dagger-mod: run `dagger generate`") + + assert_equal "Main has no function nope", JSON.parse(file)["message"] + assert_equal "dagger-mod: run `dagger generate`\n", logs + end + + # Without a frame of the module's, an error is its message and class alone; + # a SyntaxError's, without syntax_suggest's guess, and its report the first + # line, which names the file and the line. + def test_a_module_file_that_does_not_parse + error = syntax_error("class Main\nend\n\nthis is not ruby)\n") + file, logs = report_to_file(raised(error, "/usr/local/lib/ruby/4.0.0/bundled_gems.rb:60:in 'Kernel.require'", + *SDK_FRAMES)) + path = error.path + + assert_equal "#{path}:4: syntax errors found", JSON.parse(file)["message"] + assert_match(/\A#{Regexp.escape(path)}:4: syntax errors found \(SyntaxError\)\n.*> 4 \| this is not ruby\)\n/m, + logs) + refute_includes logs, "-->" + assert logs.end_with?("expecting end-of-input\n"), logs + end + + def test_an_error_without_a_message_reports_its_class + file, = report_to_file(raised(RuntimeError.new(""), "/src/lib/main.rb:3:in 'Main#fail'")) + + assert_equal "RuntimeError", JSON.parse(file)["message"] + end + + # An engine that names no file: the error as Ruby prints it, then the + # marker line the entrypoint reads, last, its message with the origin. + def test_without_a_file_the_error_goes_to_stderr_with_the_marker + logs = report(raised(RuntimeError.new("boom #{ORIGIN}"), "/src/lib/main.rb:3:in 'Main#fail'", *SDK_FRAMES), + path: nil, hint: "dagger-mod: hint") + lines = logs.lines(chomp: true) + + assert_equal "/src/lib/main.rb:3:in 'Main#fail': boom (RuntimeError)", lines.first + assert_includes logs, "\tfrom sdk/exe/dagger-mod:7:in '
'\n" + assert_equal ["dagger-mod: hint", %(::dagger-function-error::"boom #{ORIGIN}")], lines.last(2) + end + + def test_without_a_file_an_api_error_shows_its_message_and_stderr + lines = report(raised(exec_error, *SDK_FRAMES), path: nil).lines(chomp: true) + + assert_equal ["dagger-mod: Dagger::ExecError: exit code: 1", "oops", + %(::dagger-function-error::"exit code: 1 #{ORIGIN}")], lines + end + + def test_a_file_that_cannot_be_written_falls_back_to_the_marker + logs = report(raised(RuntimeError.new("boom"), "/src/lib/main.rb:3:in 'Main#fail'"), + path: "/nonexistent/dir/error.json") + + assert logs.end_with?(%(::dagger-function-error::"boom"\n)), logs + end + + def test_the_marker_message_is_cut_and_keeps_its_origins + long = "x" * (Dagger::Mod::ErrorReport::MARKER_LIMIT * 2) + marker = report(raised(RuntimeError.new("#{long} #{ORIGIN}"), "/src/lib/main.rb:3:in 'Main#fail'"), + path: nil).lines.last + message = JSON.parse(marker.delete_prefix(Dagger::Mod::ErrorReport::MARKER)) + + assert_equal "#{"x" * Dagger::Mod::ErrorReport::MARKER_LIMIT}... #{ORIGIN}", message + end + + def test_a_report_over_the_limit_is_shortened_to_fit + big = "y" * Dagger::Mod::ErrorReport::FILE_LIMIT + error = Dagger::ExecError.new([{ "message" => "#{big} #{ORIGIN}", "extensions" => { "stderr" => "#{big}end" } }], + "query") + report = Dagger::Mod::ErrorReport.file_report(error) + decoded = JSON.parse(report) + + assert_operator report.bytesize, :<=, Dagger::Mod::ErrorReport::FILE_LIMIT + assert decoded["message"].end_with?("... #{ORIGIN}"), decoded["message"][-80..] + assert decoded["values"]["stderr"].start_with?("...") && decoded["values"]["stderr"].end_with?("yend") + end + + def test_invalid_utf8_is_reported + file, = report_to_file(raised(RuntimeError.new("bad \xff byte".b), "/src/lib/main.rb:3:in 'Main#fail'")) + + assert_equal "bad \uFFFD byte", JSON.parse(file)["message"] + end + + def test_the_framework_is_the_sdk_the_clients_the_gems_and_ruby + report = Dagger::Mod::ErrorReport.for_module(module_root: "/src", sdk_root: "/src/sdk", env: {}) + framework = report.instance_variable_get(:@framework) + + assert_includes framework, "/src/sdk/" + assert_includes framework, "/src/clients/" + assert_includes framework, "#{RbConfig::CONFIG["rubylibprefix"]}/" + refute report.shows_trace?(exec_error) + assert report.shows_trace?(RuntimeError.new("boom")) + end + + private + + def exec_error + Dagger::ExecError.new([{ "message" => "exit code: 1 #{ORIGIN}", "extensions" => EXTENSIONS.dup }], "query") + end + + def raised(error, *frames) + error.set_backtrace(frames) + error + end + + def wrap(inner) + raise inner + rescue Dagger::QueryError => e + begin + yield e + rescue StandardError => wrapped + wrapped + end + end + + def syntax_error(source) + Dir.mktmpdir do |dir| + path = File.join(dir, "main.rb") + File.write(path, source) + load path + end + flunk "the source parsed" + rescue SyntaxError => e + e + end + + def reporter(path) + Dagger::Mod::ErrorReport.new(framework: FRAMEWORK, cwd: "/src", path:, stderr: (@stderr = StringIO.new)) + end + + def report(error, path:, hint: nil) + reporter(path).report(error, hint:) + @stderr.string + end + + def report_to_file(error, hint: nil) + Dir.mktmpdir do |dir| + path = File.join(dir, "error.json") + logs = report(error, path:, hint:) + [File.read(path), logs] + end + end +end From 6ba32f19377fdc188eb759f2ecdae80da46beebf Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 23:21:53 +0000 Subject: [PATCH 2/2] fix: shorten deep traces, scrub messages Address review: a stack overflow's short trace is shortened as Ruby's own printer shortens it; error_highlight's snippet is left out when the frame that raised is not the module's, which heads the trace instead; messages with invalid UTF-8 are scrubbed before any string operation; a module file that doesn't parse exits 1 again, as before, without the generate hint. Signed-off-by: Alex Suraci --- .dagger/modules/e2e/sdk/lib/dagger/mod/cli.rb | 13 ++--- .../e2e/sdk/lib/dagger/mod/error_report.rb | 54 ++++++++++++++----- .dagger/modules/e2e/sdk/sig/mod/mod.rbs | 7 ++- hack/designs/ruby-sdk-design.md | 5 +- sdk/lib/dagger/mod/cli.rb | 13 ++--- sdk/lib/dagger/mod/error_report.rb | 54 ++++++++++++++----- sdk/sig/mod/mod.rbs | 7 ++- test/mod/dispatch_test.rb | 17 ++++++ test/mod/error_report_test.rb | 43 ++++++++++++++- 9 files changed, 169 insertions(+), 44 deletions(-) diff --git a/.dagger/modules/e2e/sdk/lib/dagger/mod/cli.rb b/.dagger/modules/e2e/sdk/lib/dagger/mod/cli.rb index d28bad1..da85cdd 100644 --- a/.dagger/modules/e2e/sdk/lib/dagger/mod/cli.rb +++ b/.dagger/modules/e2e/sdk/lib/dagger/mod/cli.rb @@ -58,9 +58,10 @@ def entrypoint(options) # Runs the call, and reports the error it fails with (ErrorReport), # followed by the hint to run dagger generate after one that most - # likely follows an edit made without it. Returns the exit status: 1 - # when the module doesn't load, 2 for any other error. An exit of the - # function's own, or a signal, ends the process as it would. + # likely follows an edit made without it, such as a file or a constant + # the module no longer finds as it loads. Returns the exit status: 1 + # when the module's code doesn't load, 2 for any other error. An exit of + # the function's own, or a signal, ends the process as it would. def call(argv, input: $stdin, report: ErrorReport.for_module) loaded = false options = parse(argv) @@ -75,10 +76,10 @@ def call(argv, input: $stdin, report: ErrorReport.for_module) rescue SystemExit, SignalException raise rescue Exception => e # rubocop:disable Lint/RescueException - unloaded = !loaded && (e.is_a?(LoadError) || e.is_a?(NameError)) - stale = unloaded || STALE.any? { e.is_a?(it) } + unloadable = !loaded && (e.is_a?(ScriptError) || e.is_a?(NameError)) + stale = (unloadable && !e.is_a?(SyntaxError)) || STALE.any? { e.is_a?(it) } report.report(e, hint: stale ? "dagger-mod: #{REGENERATE_HINT}" : nil) - unloaded ? 1 : 2 + unloadable ? 1 : 2 end def parse_request(text) diff --git a/.dagger/modules/e2e/sdk/lib/dagger/mod/error_report.rb b/.dagger/modules/e2e/sdk/lib/dagger/mod/error_report.rb index f793a3f..111d8e9 100644 --- a/.dagger/modules/e2e/sdk/lib/dagger/mod/error_report.rb +++ b/.dagger/modules/e2e/sdk/lib/dagger/mod/error_report.rb @@ -37,6 +37,15 @@ class ErrorReport # reports it from. ORIGIN = /\s*\[traceparent:[0-9a-f]{32}-[0-9a-f]{16}\]/ + # The encodings whose bytes are read as UTF-8. + RAW = [Encoding::UTF_8, Encoding::BINARY].freeze + + # How Ruby shortens the trace of a stack overflow: the first frames, the + # count of those it leaves out, the last frames (error.c, print_backtrace). + TRACE_HEAD = 8 + TRACE_TAIL = 5 + TRACE_MAX = TRACE_HEAD + TRACE_TAIL + 5 + # The report for the module the process runs, whose code is everything # but the SDK, the clients generation writes, the installed gems (Gem.path # holds Bundler's path once bundler/setup ran) and Ruby's own library. A @@ -115,7 +124,7 @@ def short_trace(error) def shows_trace?(error) return false if error.is_a?(Mod::Error) - !(error.is_a?(::Dagger::QueryError) && ORIGIN.match?(error.message)) + !(error.is_a?(::Dagger::QueryError) && ORIGIN.match?(self.class.utf8(error.message))) end # The error's message, or its class when it has none: the engine takes @@ -123,7 +132,7 @@ def shows_trace?(error) # is the file's annotated source, which the function's logs show; its # first line names the file and the line. def self.message_of(error) - message = error.message + message = utf8(error.message) message = message.lines.first.to_s.chomp if error.is_a?(SyntaxError) message.strip.empty? ? error.class.name.to_s : message end @@ -167,9 +176,14 @@ def self.shortened(value) end end + # The value with each string in UTF-8, what can't be read replaced: a + # message may hold any bytes, such as a command's output. def self.utf8(value) case value - when String then value.dup.force_encoding(Encoding::UTF_8).scrub + when String + return value.encode(Encoding::UTF_8, invalid: :replace, undef: :replace) unless RAW.include?(value.encoding) + + value.dup.force_encoding(Encoding::UTF_8).scrub when Hash then value.to_h { |key, item| [utf8(key.to_s), utf8(item)] } when Array then value.map { utf8(it) } else value @@ -207,21 +221,35 @@ def write_marker(error) def sdk_error?(error) = error.is_a?(Mod::Error) || error.is_a?(::Dagger::QueryError) # One error of the chain, as Ruby's full_message gives it: the first - # frame, the message and its class, then a line for each other frame. + # frame, the message and its class, then a line for each other frame, + # those of a stack overflow shortened as Ruby shortens them. def describe(error) frames = module_frames(error) - text = without_origins(detailed_message(error)).rstrip - text = "#{frames.first}: #{text}" unless frames.empty? - "#{text}\n#{frames.drop(1).map { "\tfrom #{it}\n" }.join}" + text = without_origins(detailed_message(error, raised_here: frames.first == error.backtrace&.first)).rstrip + return "#{text}\n" if frames.empty? + + "#{frames.first}: #{text}\n#{from_lines(error, frames)}" end - # Ruby's message and class. SyntaxError's is its own: syntax_suggest's + def from_lines(error, frames) + lines = frames.drop(1).map { "\tfrom #{it}\n" } + return lines.join unless error.is_a?(SystemStackError) && frames.size > TRACE_MAX + + skipped = frames.size - TRACE_MAX + 1 + [*lines.first(TRACE_HEAD), "\t ... #{skipped} levels...\n", *lines.drop(TRACE_HEAD + skipped)].join + end + + # Ruby's message and class. error_highlight's snippet is of the frame + # that raised, so it goes when that frame is not the module's, which + # heads the trace instead. SyntaxError's is its own: syntax_suggest's # guess at the unmatched code reads the file again, and it points at a # module's first lines as often as at what doesn't parse. - def detailed_message(error) - return error.detailed_message(highlight: false) unless error.is_a?(SyntaxError) - - Exception.instance_method(:detailed_message).bind_call(error, highlight: false) + def detailed_message(error, raised_here:) + if error.is_a?(SyntaxError) + Exception.instance_method(:detailed_message).bind_call(error, highlight: false) + else + error.detailed_message(highlight: false, error_highlight: raised_here) + end end # A frame's path is its location's, when the frame is still the one @@ -244,7 +272,7 @@ def module_file?(path) @framework.none? { full.start_with?(it) } end - def without_origins(text) = text.gsub(ORIGIN, "") + def without_origins(text) = self.class.utf8(text).gsub(ORIGIN, "") end end end diff --git a/.dagger/modules/e2e/sdk/sig/mod/mod.rbs b/.dagger/modules/e2e/sdk/sig/mod/mod.rbs index 726312b..02d810e 100644 --- a/.dagger/modules/e2e/sdk/sig/mod/mod.rbs +++ b/.dagger/modules/e2e/sdk/sig/mod/mod.rbs @@ -394,6 +394,10 @@ module Dagger SHORTENED_LENGTH: Integer MARKER_LIMIT: Integer ORIGIN: Regexp + RAW: Array[Encoding] + TRACE_HEAD: Integer + TRACE_TAIL: Integer + TRACE_MAX: Integer @framework: Array[String] @cwd: String @@ -423,7 +427,8 @@ module Dagger def write_marker: (Exception error) -> void def sdk_error?: (Exception error) -> bool def describe: (Exception error) -> String - def detailed_message: (Exception error) -> String + def from_lines: (Exception error, Array[String] frames) -> String + def detailed_message: (Exception error, raised_here: bool) -> String def module_frames: (Exception error) -> Array[String] def module_file?: (String? path) -> bool def without_origins: (String text) -> String diff --git a/hack/designs/ruby-sdk-design.md b/hack/designs/ruby-sdk-design.md index 37c3b16..a2dadc6 100644 --- a/hack/designs/ruby-sdk-design.md +++ b/hack/designs/ruby-sdk-design.md @@ -176,8 +176,9 @@ sequenceDiagram `dagger-mod call` lets what the module's code raises propagate as it is, and reports it (`Dagger::Mod::ErrorReport`), then exits 2, so its exec is not -cached; 1 when the module does not load. An `exit` of the function's own ends -the process with its status, and reports nothing. +cached; 1 when the module's code does not load (a `ScriptError` or a +`NameError` as it loads). An `exit` of the function's own ends the process +with its status, and reports nothing. - On an engine that sets `DAGGER_FUNCTION_ERROR_PATH`, the report goes to that file: `{"message", "values"}`, the message whole, its `[traceparent:…]` diff --git a/sdk/lib/dagger/mod/cli.rb b/sdk/lib/dagger/mod/cli.rb index d28bad1..da85cdd 100644 --- a/sdk/lib/dagger/mod/cli.rb +++ b/sdk/lib/dagger/mod/cli.rb @@ -58,9 +58,10 @@ def entrypoint(options) # Runs the call, and reports the error it fails with (ErrorReport), # followed by the hint to run dagger generate after one that most - # likely follows an edit made without it. Returns the exit status: 1 - # when the module doesn't load, 2 for any other error. An exit of the - # function's own, or a signal, ends the process as it would. + # likely follows an edit made without it, such as a file or a constant + # the module no longer finds as it loads. Returns the exit status: 1 + # when the module's code doesn't load, 2 for any other error. An exit of + # the function's own, or a signal, ends the process as it would. def call(argv, input: $stdin, report: ErrorReport.for_module) loaded = false options = parse(argv) @@ -75,10 +76,10 @@ def call(argv, input: $stdin, report: ErrorReport.for_module) rescue SystemExit, SignalException raise rescue Exception => e # rubocop:disable Lint/RescueException - unloaded = !loaded && (e.is_a?(LoadError) || e.is_a?(NameError)) - stale = unloaded || STALE.any? { e.is_a?(it) } + unloadable = !loaded && (e.is_a?(ScriptError) || e.is_a?(NameError)) + stale = (unloadable && !e.is_a?(SyntaxError)) || STALE.any? { e.is_a?(it) } report.report(e, hint: stale ? "dagger-mod: #{REGENERATE_HINT}" : nil) - unloaded ? 1 : 2 + unloadable ? 1 : 2 end def parse_request(text) diff --git a/sdk/lib/dagger/mod/error_report.rb b/sdk/lib/dagger/mod/error_report.rb index f793a3f..111d8e9 100644 --- a/sdk/lib/dagger/mod/error_report.rb +++ b/sdk/lib/dagger/mod/error_report.rb @@ -37,6 +37,15 @@ class ErrorReport # reports it from. ORIGIN = /\s*\[traceparent:[0-9a-f]{32}-[0-9a-f]{16}\]/ + # The encodings whose bytes are read as UTF-8. + RAW = [Encoding::UTF_8, Encoding::BINARY].freeze + + # How Ruby shortens the trace of a stack overflow: the first frames, the + # count of those it leaves out, the last frames (error.c, print_backtrace). + TRACE_HEAD = 8 + TRACE_TAIL = 5 + TRACE_MAX = TRACE_HEAD + TRACE_TAIL + 5 + # The report for the module the process runs, whose code is everything # but the SDK, the clients generation writes, the installed gems (Gem.path # holds Bundler's path once bundler/setup ran) and Ruby's own library. A @@ -115,7 +124,7 @@ def short_trace(error) def shows_trace?(error) return false if error.is_a?(Mod::Error) - !(error.is_a?(::Dagger::QueryError) && ORIGIN.match?(error.message)) + !(error.is_a?(::Dagger::QueryError) && ORIGIN.match?(self.class.utf8(error.message))) end # The error's message, or its class when it has none: the engine takes @@ -123,7 +132,7 @@ def shows_trace?(error) # is the file's annotated source, which the function's logs show; its # first line names the file and the line. def self.message_of(error) - message = error.message + message = utf8(error.message) message = message.lines.first.to_s.chomp if error.is_a?(SyntaxError) message.strip.empty? ? error.class.name.to_s : message end @@ -167,9 +176,14 @@ def self.shortened(value) end end + # The value with each string in UTF-8, what can't be read replaced: a + # message may hold any bytes, such as a command's output. def self.utf8(value) case value - when String then value.dup.force_encoding(Encoding::UTF_8).scrub + when String + return value.encode(Encoding::UTF_8, invalid: :replace, undef: :replace) unless RAW.include?(value.encoding) + + value.dup.force_encoding(Encoding::UTF_8).scrub when Hash then value.to_h { |key, item| [utf8(key.to_s), utf8(item)] } when Array then value.map { utf8(it) } else value @@ -207,21 +221,35 @@ def write_marker(error) def sdk_error?(error) = error.is_a?(Mod::Error) || error.is_a?(::Dagger::QueryError) # One error of the chain, as Ruby's full_message gives it: the first - # frame, the message and its class, then a line for each other frame. + # frame, the message and its class, then a line for each other frame, + # those of a stack overflow shortened as Ruby shortens them. def describe(error) frames = module_frames(error) - text = without_origins(detailed_message(error)).rstrip - text = "#{frames.first}: #{text}" unless frames.empty? - "#{text}\n#{frames.drop(1).map { "\tfrom #{it}\n" }.join}" + text = without_origins(detailed_message(error, raised_here: frames.first == error.backtrace&.first)).rstrip + return "#{text}\n" if frames.empty? + + "#{frames.first}: #{text}\n#{from_lines(error, frames)}" end - # Ruby's message and class. SyntaxError's is its own: syntax_suggest's + def from_lines(error, frames) + lines = frames.drop(1).map { "\tfrom #{it}\n" } + return lines.join unless error.is_a?(SystemStackError) && frames.size > TRACE_MAX + + skipped = frames.size - TRACE_MAX + 1 + [*lines.first(TRACE_HEAD), "\t ... #{skipped} levels...\n", *lines.drop(TRACE_HEAD + skipped)].join + end + + # Ruby's message and class. error_highlight's snippet is of the frame + # that raised, so it goes when that frame is not the module's, which + # heads the trace instead. SyntaxError's is its own: syntax_suggest's # guess at the unmatched code reads the file again, and it points at a # module's first lines as often as at what doesn't parse. - def detailed_message(error) - return error.detailed_message(highlight: false) unless error.is_a?(SyntaxError) - - Exception.instance_method(:detailed_message).bind_call(error, highlight: false) + def detailed_message(error, raised_here:) + if error.is_a?(SyntaxError) + Exception.instance_method(:detailed_message).bind_call(error, highlight: false) + else + error.detailed_message(highlight: false, error_highlight: raised_here) + end end # A frame's path is its location's, when the frame is still the one @@ -244,7 +272,7 @@ def module_file?(path) @framework.none? { full.start_with?(it) } end - def without_origins(text) = text.gsub(ORIGIN, "") + def without_origins(text) = self.class.utf8(text).gsub(ORIGIN, "") end end end diff --git a/sdk/sig/mod/mod.rbs b/sdk/sig/mod/mod.rbs index 726312b..02d810e 100644 --- a/sdk/sig/mod/mod.rbs +++ b/sdk/sig/mod/mod.rbs @@ -394,6 +394,10 @@ module Dagger SHORTENED_LENGTH: Integer MARKER_LIMIT: Integer ORIGIN: Regexp + RAW: Array[Encoding] + TRACE_HEAD: Integer + TRACE_TAIL: Integer + TRACE_MAX: Integer @framework: Array[String] @cwd: String @@ -423,7 +427,8 @@ module Dagger def write_marker: (Exception error) -> void def sdk_error?: (Exception error) -> bool def describe: (Exception error) -> String - def detailed_message: (Exception error) -> String + def from_lines: (Exception error, Array[String] frames) -> String + def detailed_message: (Exception error, raised_here: bool) -> String def module_frames: (Exception error) -> Array[String] def module_file?: (String? path) -> bool def without_origins: (String text) -> String diff --git a/test/mod/dispatch_test.rb b/test/mod/dispatch_test.rb index cc72ad9..a86a8d4 100644 --- a/test/mod/dispatch_test.rb +++ b/test/mod/dispatch_test.rb @@ -229,6 +229,23 @@ def test_a_call_the_module_no_longer_matches_shows_its_error_and_the_hint end end + # A module file that doesn't parse shows Ruby's own error, without the + # hint, and reports its first line, which names the file and the line. + def test_a_module_that_does_not_parse_reports_ruby_syntax_error + Dir.mktmpdir do |dir| + write_module(dir) + File.write(File.join(dir, "main.rb"), "this is not ruby)\n", mode: "a") + report = File.join(dir, "error.json") + out, status = run_cli(dir, "greet", "{}", env: { Dagger::Mod::ErrorReport::PATH_ENV => report }) + message = JSON.parse(File.read(report))["message"] + + assert_equal 1, status.exitstatus + assert_match(/\A\S+main\.rb:\d+: syntax errors found\z/, message) + assert out.start_with?("#{message} (SyntaxError)\n"), out + refute_includes out, "dagger generate" + end + end + def test_a_call_without_signatures_asks_for_dagger_generate Dir.mktmpdir do |dir| write_module(dir) diff --git a/test/mod/error_report_test.rb b/test/mod/error_report_test.rb index 0cd2f49..37359e8 100644 --- a/test/mod/error_report_test.rb +++ b/test/mod/error_report_test.rb @@ -121,9 +121,48 @@ def test_a_report_over_the_limit_is_shortened_to_fit end def test_invalid_utf8_is_reported - file, = report_to_file(raised(RuntimeError.new("bad \xff byte".b), "/src/lib/main.rb:3:in 'Main#fail'")) + ["bad \xff byte".b, "bad \xff byte".dup.force_encoding(Encoding::UTF_8)].each do |message| + error = raised(RuntimeError.new(message), "/src/lib/main.rb:3:in 'Main#fail'") + file, logs = report_to_file(error) - assert_equal "bad \uFFFD byte", JSON.parse(file)["message"] + assert_equal "bad \uFFFD byte", JSON.parse(file)["message"] + assert_includes logs, "bad \uFFFD byte (RuntimeError)" + assert_includes report(error, path: nil), %(::dagger-function-error::"bad \uFFFD byte") + end + end + + # Ruby prints the first frames of a stack overflow, how many it leaves + # out, and the last. + def test_a_stack_overflow_is_shortened_as_ruby_shortens_it + frames = (1..30).map { "/src/lib/main.rb:#{it}:in 'Main#deep'" } + _, logs = report_to_file(raised(SystemStackError.new("stack level too deep"), *frames)) + lines = logs.lines(chomp: true) + + assert_equal "/src/lib/main.rb:1:in 'Main#deep': stack level too deep (SystemStackError)", lines.first + assert_equal (2..9).map { "\tfrom /src/lib/main.rb:#{it}:in 'Main#deep'" }, lines[1..8] + assert_equal "\t ... 13 levels...", lines[9] + assert_equal (23..30).map { "\tfrom /src/lib/main.rb:#{it}:in 'Main#deep'" }, lines[10..] + end + + # error_highlight points at the code of the frame that raised: not the + # module's, which heads the trace, when a gem raised. + def test_an_error_raised_in_a_gem_has_no_snippet_of_the_gems_code + Dir.mktmpdir do |gems| + File.write(File.join(gems, "shout.rb"), "module Shout\n def self.up(value) = value.upcase\nend\n") + load File.join(gems, "shout.rb") + error = begin + Shout.up(nil) + rescue NoMethodError => e + e + end + stderr = StringIO.new + Dagger::Mod::ErrorReport.new(framework: ["#{gems}/"], cwd: "/", path: File.join(gems, "error.json"), stderr:) + .report(error) + + assert_match(/\A\S+error_report_test\.rb:\d+:in .*: undefined method 'upcase' for nil \(NoMethodError\)\n\tfrom /, + stderr.string) + refute_includes stderr.string, "^^^" + end end def test_the_framework_is_the_sdk_the_clients_the_gems_and_ruby