From 115d8d91eef6b49012ea66112adc0af0ef5fc48c Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sat, 21 Nov 2026 20:10:00 +0000 Subject: [PATCH 1/6] Bump sdk-helpers to v1.0.11 sdk-helpers v1.0.9 no longer compiles under current Dang: its main.dang:147 writes a nullable type pattern in a rescue arm, which is now rejected ("a type pattern is the non-null type its arm binds: write `error: Error! =>`"). Every php-sdk generation fails on it. v1.0.11, which go-sdk already uses, fixes it. Signed-off-by: Alex Suraci --- dagger-module.toml | 2 +- dagger.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dagger-module.toml b/dagger-module.toml index 39b9c94..8ca3eb8 100644 --- a/dagger-module.toml +++ b/dagger-module.toml @@ -6,4 +6,4 @@ engineVersion = "v1.0.0-beta.27" [[dependencies]] name = "sdk-helpers" - source = "github.com/dagger/sdk-helpers@v1.0.9" + source = "github.com/dagger/sdk-helpers@v1.0.11" diff --git a/dagger.lock b/dagger.lock index be7c05d..1a38990 100644 --- a/dagger.lock +++ b/dagger.lock @@ -1,5 +1,5 @@ [["version","2"]] -["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.9"]],"refs/tags/v1.0.9"] -["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.9"],"daffbc01a1b3f3df7b1c417a7d2c83cd06d1bd33"] +["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.11"]],"refs/tags/v1.0.11"] +["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.11"],"3be7456c40d9206b648ac44e418f30aa79bc6190"] ["","git-sha",["https://github.com/dagger/dagger","refs/tags/v1.0.0-beta.11"],"a4e1e4ff663e5e51c2b96c2c0772f3d2f00cfb94"] ["","oci-sha",["docker.io/library/golang:1.25-alpine"],"sha256:1ae0735f00daffa3aaf1363a5184c0d2dc55c78e3db4ec70241cdac97bf84b59"] \ No newline at end of file From 1fe08a1443bced4e9742df3e35d3d592838d621c Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 09:17:57 +0000 Subject: [PATCH 2/6] module: report function errors in a file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On an engine that sets DAGGER_FUNCTION_ERROR_PATH (dagger/dagger#15249), a failed call writes {"message", "values"} there and exits 2: the message in full, with its [traceparent:…] origins, and the values the extensions of the QueryError it is or wraps, so a caller gets a typed ExecError. The generated entrypoint raises the exec error unchanged when it carries the engine's functionError. Older engines, or a file that can't be written, get the full trace plus a ::dagger-function-error:: marker line on stderr, which the entrypoint reads; without one, as when the function exits by itself, the exec's own error, exit code and all, is raised. Before, the entrypoint raised the dispatcher's whole stderr as the message, and a call exited with the inner exec's code. In error-file mode the function's logs get only a short trace, through the module's own frames (not the SDK's, its generated clients' or vendor/'s), previous errors first, without origins; a file that doesn't parse reads as PHP reports it. An API error whose origin the engine shows prints nothing. The entrypoint also declares prebuild, the module with its Composer dependencies installed, so the engine builds it as the module's build and a failed install shows under it with Composer's output; call() syncs it before the rescue for the same reason. Signed-off-by: Alex Suraci --- sdk/bin/dagger-module | 22 +- sdk/src/Module/DangEntrypointRenderer.php | 43 ++- sdk/src/Module/FunctionError.php | 290 ++++++++++++++++++ .../Module/DangEntrypointRendererTest.php | 38 ++- sdk/tests/Unit/Module/FunctionErrorTest.php | 274 +++++++++++++++++ 5 files changed, 650 insertions(+), 17 deletions(-) create mode 100644 sdk/src/Module/FunctionError.php create mode 100644 sdk/tests/Unit/Module/FunctionErrorTest.php diff --git a/sdk/bin/dagger-module b/sdk/bin/dagger-module index c86f3d3..7d7eeb6 100755 --- a/sdk/bin/dagger-module +++ b/sdk/bin/dagger-module @@ -5,6 +5,7 @@ use Dagger\Dagger; use Dagger\Module\CallDispatcher; use Dagger\Module\DangEntrypointRenderer; use Dagger\Module\Description; +use Dagger\Module\FunctionError; use Dagger\Module\InterfaceClients; use Dagger\Module\ValueCodec; use GraphQL\Exception\QueryError; @@ -72,12 +73,21 @@ try { default: fail(USAGE, 2); } -} catch (QueryError $e) { - $extensions = $e->getErrorDetails()['extensions'] ?? []; +} catch (Throwable $t) { + if ($mode === 'call') { + // A failed call exits 2, so that its exec isn't cached, and reports + // the function's error to the engine; see FunctionError. + $path = getenv(FunctionError::PATH_ENV); + FunctionError::forModule(dirname(__DIR__), (string) getcwd()) + ->report($t, $path === false ? null : $path, STDERR); + exit(2); + } + if (!$t instanceof QueryError) { + fwrite(STDERR, sprintf("dagger-module: %s: %s\n%s\n", $t::class, $t->getMessage(), $t->getTraceAsString())); + exit(1); + } + $extensions = $t->getErrorDetails()['extensions'] ?? []; fwrite(STDOUT, $extensions['stdout'] ?? ''); - fwrite(STDERR, $e->getMessage() . "\n" . ($extensions['stderr'] ?? '')); + fwrite(STDERR, $t->getMessage() . "\n" . ($extensions['stderr'] ?? '')); exit($extensions['exitCode'] ?? 1); -} catch (Throwable $t) { - fwrite(STDERR, sprintf("dagger-module: %s: %s\n%s\n", $t::class, $t->getMessage(), $t->getTraceAsString())); - exit(1); } diff --git a/sdk/src/Module/DangEntrypointRenderer.php b/sdk/src/Module/DangEntrypointRenderer.php index 67a9448..09454f1 100644 --- a/sdk/src/Module/DangEntrypointRenderer.php +++ b/sdk/src/Module/DangEntrypointRenderer.php @@ -289,6 +289,13 @@ private static function wrap(string $call, array $body): array ModuleTypes().all } + # The module with its Composer dependencies 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 Composer's output. + pub prebuild: File! { + runtime.file("vendor/autoload.php") + } + pub call( receiverType: String!, receiverValue: JSON, @@ -302,7 +309,10 @@ private static function wrap(string $call, array $body): array fnName: fnName, fnArgs: fnArgs, }}) - let result = runtime + # A failed install stays out of the rescue below, so it fails the call + # with its own error. + 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 @@ -311,17 +321,34 @@ private static function wrap(string $call, array $body): array .withExec(["php", "sdk/bin/dagger-module", "call", "--output", "/dagger/result.json"], stdin: request, experimentalPrivilegedNesting: true) .file("/dagger/result.json") .contents rescue { - # From v1.0.0-beta.27 an exec error's message carries only the exit code. - # Its extensions hold the stderr, capped by the engine at 100 KiB. - err: GraphQLError => { - let stderr = (JSON.decode(err.extensions) :: {{stderr: String}}).stderr ?? "" - if (stderr == "") { raise err } - raise stderr - } + err: GraphQLError => raiseFunctionError(err) } (result :: JSON!) } + # An engine that gives the dispatcher a file for the function's error + # (DAGGER_FUNCTION_ERROR_PATH) puts the error the dispatcher 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 dispatcher couldn't write, the exec error carries the end of + # the dispatcher'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 + # again. + 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) + } + let runtime: Container! { PhpModuleBuild(contextDir: currentModule.contextDirectory, subPath: currentModule.sourceSubpath).installed } diff --git a/sdk/src/Module/FunctionError.php b/sdk/src/Module/FunctionError.php new file mode 100644 index 0000000..b08f791 --- /dev/null +++ b/sdk/src/Module/FunctionError.php @@ -0,0 +1,290 @@ + $frameworkPaths the directories whose code isn't the + * module's own: the SDK's and the installed dependencies', each ending in / + */ + public function __construct(private array $frameworkPaths) + { + } + + /** + * The module's code is everything but the SDK, its generated clients + * included, and what Composer installed into vendor/. A library the + * module installs from a path of its own resolves to that path, so its + * frames stay. + */ + public static function forModule(string $sdkRoot, string $moduleRoot): self + { + $paths = []; + foreach ([$sdkRoot, "$moduleRoot/vendor"] as $path) { + $paths[] = rtrim($path, '/') . '/'; + $real = realpath($path); + if ($real !== false) { + $paths[] = rtrim($real, '/') . '/'; + } + } + + return new self(array_values(array_unique($paths))); + } + + /** + * Report $error: in the file at $path when there is one and it can be + * written, else with the marker. Diagnostics go to $stderr. + * + * @param resource $stderr + */ + public function report(Throwable $error, ?string $path, $stderr): void + { + if ($path !== null && $path !== '' && self::writeFile($path, $error)) { + if (!self::hasOrigin($error)) { + fwrite($stderr, $this->shortTrace($error)); + } + return; + } + + fwrite($stderr, sprintf("dagger-module: %s\n", $error)); + fwrite($stderr, self::MARKER . json_encode(self::truncate(self::messageOf($error)), self::JSON_FLAGS) . "\n"); + } + + /** + * Whether the error is an API error that names its origin, the call that + * failed, which the engine shows with its own logs. An error of the + * module's own, even one that wraps such an API error, is the module's + * to show. + */ + public static function hasOrigin(Throwable $error): bool + { + return $error instanceof QueryError && preg_match(self::ORIGIN, $error->getMessage()) === 1; + } + + /** + * The report the engine reads: `{"message": ..., "values": {...}}`, the + * error's message in full, with any origin it names, and the extensions + * of the GraphQL error it is or wraps, 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. + */ + public static function fileReport(Throwable $error): string + { + $message = self::messageOf($error); + $values = self::values($error); + $report = self::encodeReport($message, $values); + if (strlen($report) <= self::FILE_LIMIT) { + return $report; + } + + if (strlen($message) > self::SHORTENED_LENGTH) { + preg_match_all(self::ORIGIN, substr($message, self::SHORTENED_LENGTH), $origins); + $message = mb_strcut($message, 0, self::SHORTENED_LENGTH) . '...' . implode('', $origins[0]); + } + $report = self::encodeReport($message, (array) self::shortened($values)); + if (strlen($report) <= self::FILE_LIMIT) { + return $report; + } + + return self::encodeReport($message, []); + } + + /** + * The error as PHP prints an uncaught one, through the module's own + * frames only, previous errors first, and without the origins the + * messages name. A file that doesn't parse reads as PHP reports it. + */ + public function shortTrace(Throwable $error): string + { + $chain = []; + for ($e = $error; $e !== null && !in_array($e, $chain, true); $e = $e->getPrevious()) { + $chain[] = $e; + } + + $parts = []; + foreach (array_reverse($chain) as $e) { + $parts[] = $this->describe($e); + } + + return implode("\nNext ", $parts); + } + + private function describe(Throwable $e): string + { + $message = self::withoutOrigins($e->getMessage()); + if ($e instanceof CompileError && $this->isModuleFile($e->getFile())) { + $kind = $e instanceof ParseError ? 'Parse error' : 'Fatal error'; + return sprintf("PHP %s: %s in %s on line %d\n", $kind, $message, $e->getFile(), $e->getLine()); + } + + $text = $e::class . ($message === '' ? '' : ": $message"); + if ($this->isModuleFile($e->getFile())) { + $text .= sprintf(' in %s:%d', $e->getFile(), $e->getLine()); + } + $text .= "\n"; + + $frames = []; + foreach ($e->getTrace() as $frame) { + $file = $frame['file'] ?? null; + if ($file === null || !$this->isModuleFile($file)) { + continue; + } + $function = isset($frame['class']) + ? $frame['class'] . ($frame['type'] ?? '::') . $frame['function'] + : $frame['function']; + $frames[] = sprintf('#%d %s(%d): %s()', count($frames), $file, $frame['line'] ?? 0, $function); + } + if ($frames !== []) { + $text .= "Stack trace:\n" . implode("\n", $frames) . "\n"; + } + + return $text; + } + + private function isModuleFile(string $file): bool + { + if ($file === '' || !str_starts_with($file, '/')) { + return false; + } + foreach ($this->frameworkPaths as $path) { + if (str_starts_with($file, $path)) { + return false; + } + } + + return true; + } + + private static function writeFile(string $path, Throwable $error): bool + { + try { + $report = self::fileReport($error); + } catch (JsonException) { + return false; + } + + return @file_put_contents($path, $report) === strlen($report); + } + + /** + * The error's message, or its class when it has none: the engine takes + * a report with an empty message for plain text. + */ + private static function messageOf(Throwable $error): string + { + $message = $error->getMessage(); + + return trim($message) === '' ? $error::class : $message; + } + + /** + * The extensions of the GraphQL error that the error is or wraps, or none. + * + * @return array + */ + private static function values(Throwable $error): array + { + $seen = []; + for ($e = $error; $e !== null && !in_array($e, $seen, true); $e = $e->getPrevious()) { + $seen[] = $e; + if ($e instanceof QueryError) { + $extensions = $e->getErrorDetails()['extensions'] ?? []; + return is_array($extensions) ? $extensions : []; + } + } + + return []; + } + + /** @param array $values */ + private static function encodeReport(string $message, array $values): string + { + return json_encode( + ['message' => $message, 'values' => $values === [] ? new stdClass() : $values], + self::JSON_FLAGS, + ); + } + + /** + * The value with each string longer than SHORTENED_LENGTH, at any depth, + * cut to its end. + */ + private static function shortened(mixed $value): mixed + { + if (is_string($value) && strlen($value) > self::SHORTENED_LENGTH) { + $start = strlen($value) - self::SHORTENED_LENGTH; + // Not in the middle of a UTF-8 sequence. + while ($start < strlen($value) && (ord($value[$start]) & 0xC0) === 0x80) { + $start++; + } + return '...' . substr($value, $start); + } + if (is_array($value)) { + return array_map(self::shortened(...), $value); + } + + return $value; + } + + private static function truncate(string $message): string + { + return strlen($message) <= self::MARKER_LIMIT ? $message : mb_strcut($message, 0, self::MARKER_LIMIT) . '...'; + } + + private static function withoutOrigins(string $message): string + { + return (string) preg_replace(self::ORIGIN, '', $message); + } +} diff --git a/sdk/tests/Unit/Module/DangEntrypointRendererTest.php b/sdk/tests/Unit/Module/DangEntrypointRendererTest.php index bee440e..eeb1be0 100644 --- a/sdk/tests/Unit/Module/DangEntrypointRendererTest.php +++ b/sdk/tests/Unit/Module/DangEntrypointRendererTest.php @@ -6,6 +6,7 @@ use Dagger\Module\DangEntrypointRenderer; use Dagger\Module\Description; +use Dagger\Module\FunctionError; use Dagger\ModuleNaming; use Dagger\ValueObject\DaggerEnum; use Dagger\ValueObject\DaggerEnumCase; @@ -247,15 +248,46 @@ public function itRendersTheCallContract(): void self::assertStringContainsString('experimentalPrivilegedNesting: true)', $main); self::assertStringContainsString('.file("/dagger/result.json")', $main); self::assertStringContainsString('.contents rescue {', $main); - self::assertStringContainsString('err: GraphQLError =>', $main); - self::assertStringContainsString('{ raise err }', $main); - self::assertStringContainsString('raise stderr', $main); + self::assertStringContainsString('err: GraphQLError => raiseFunctionError(err)', $main); + self::assertStringContainsString( + " let installed = runtime.sync\n let result = installed\n", + $main, + 'a failed install stays out of the rescue', + ); + self::assertStringContainsString( + "pub prebuild: File! {\n runtime.file(\"vendor/autoload.php\")\n }", + $main, + ); + self::assertStringNotContainsString('raise stderr', $main); self::assertStringContainsString( 'PhpModuleBuild(contextDir: currentModule.contextDirectory, subPath: currentModule.sourceSubpath).installed', $main, ); } + /** + * The exec error is raised as it is when the engine read the function's + * error from its file; otherwise the marker line, then the exec error. + */ + #[Test] + public function itRaisesTheFunctionError(): void + { + $main = DangEntrypointRenderer::renderMain('v1.0.0-beta.21'); + + self::assertStringContainsString( + "let reported = ((JSON.decode(err.extensions) :: {{functionError: {{message: String, id: String}}}}).functionError != null) rescue false\n" + . " if (reported) {\n" + . " raise err\n" + . " }\n" + . ' let marker = "' . FunctionError::MARKER . "\"\n", + $main, + ); + self::assertStringContainsString( + 'raise ((JSON.decode(lines.takeLast(1).join("").trimPrefix(marker)) :: String!) rescue err.message)', + $main, + ); + } + #[Test] public function itWritesTheSameFilesTwice(): void { diff --git a/sdk/tests/Unit/Module/FunctionErrorTest.php b/sdk/tests/Unit/Module/FunctionErrorTest.php new file mode 100644 index 0000000..dafd99e --- /dev/null +++ b/sdk/tests/Unit/Module/FunctionErrorTest.php @@ -0,0 +1,274 @@ + 'EXEC_ERROR', + 'cmd' => ['sh', '-c', 'exit 1'], + 'exitCode' => 1, + 'stdout' => "exec stdout\n", + 'stderr' => "exec stderr\n", + ]; + + /** @var list */ + private array $files = []; + + protected function tearDown(): void + { + foreach ($this->files as $file) { + @unlink($file); + } + } + + /** + * The SDK, PHPUnit among the installed dependencies, is the framework; + * this file stands for the module's code. + */ + private function functionError(): FunctionError + { + $sdk = dirname(__DIR__, 3); + + return FunctionError::forModule("$sdk/src", $sdk); + } + + /** @param array $extensions */ + private static function queryError(string $message, array $extensions = []): QueryError + { + $error = ['message' => $message, 'path' => ['container', 'stdout']]; + if ($extensions !== []) { + $error['extensions'] = $extensions; + } + + return new QueryError(['errors' => [$error], 'data' => null]); + } + + private static function failNatively(): never + { + throw new RuntimeException('function failed natively'); + } + + private static function caught(callable $fail): Throwable + { + try { + $fail(); + } catch (Throwable $error) { + return $error; + } + self::fail('nothing was thrown'); + } + + private function tempFile(): string + { + $file = (string) tempnam(sys_get_temp_dir(), 'function-error-'); + $this->files[] = $file; + + return $file; + } + + /** @return array{string, string} what report wrote to the file and to stderr */ + private function report(Throwable $error, ?string $path): array + { + $stderr = fopen('php://memory', 'w+'); + self::assertNotFalse($stderr); + $this->functionError()->report($error, $path, $stderr); + rewind($stderr); + $logs = (string) stream_get_contents($stderr); + fclose($stderr); + + return [$path === null || !is_file($path) ? '' : (string) file_get_contents($path), $logs]; + } + + #[Test] + public function itReportsAnApiErrorWithItsExtensions(): void + { + $report = json_decode( + FunctionError::fileReport(self::queryError('exit code: 1' . self::ORIGIN, self::EXEC_ERROR)), + true, + flags: JSON_THROW_ON_ERROR, + ); + + self::assertSame(['message' => 'exit code: 1' . self::ORIGIN, 'values' => self::EXEC_ERROR], $report); + } + + #[Test] + public function itReportsTheExtensionsOfAWrappedApiError(): void + { + $inner = self::queryError('exit code: 1' . self::ORIGIN, self::EXEC_ERROR); + $error = new RuntimeException('ran a failing command: ' . $inner->getMessage(), previous: $inner); + + $report = json_decode(FunctionError::fileReport($error), true, flags: JSON_THROW_ON_ERROR); + + self::assertSame('ran a failing command: exit code: 1' . self::ORIGIN, $report['message']); + self::assertSame(self::EXEC_ERROR, $report['values']); + } + + #[Test] + public function itReportsValuesAsAnObject(): void + { + self::assertSame( + '{"message":"function failed","values":{}}', + FunctionError::fileReport(new RuntimeException('function failed')), + ); + } + + #[Test] + public function itNamesTheClassOfAnErrorWithoutAMessage(): void + { + self::assertSame( + '{"message":"RuntimeException","values":{}}', + FunctionError::fileReport(new RuntimeException(' ')), + ); + } + + #[Test] + public function itShortensAReportTheEngineWouldNotRead(): void + { + $long = str_repeat('x', FunctionError::FILE_LIMIT); + $error = self::queryError($long . self::ORIGIN, ['stdout' => $long . 'end', 'exitCode' => 1]); + + $file = FunctionError::fileReport($error); + $report = json_decode($file, true, flags: JSON_THROW_ON_ERROR); + + self::assertLessThanOrEqual(FunctionError::FILE_LIMIT, strlen($file)); + self::assertStringEndsWith('...' . self::ORIGIN, $report['message']); + self::assertSame(FunctionError::SHORTENED_LENGTH + 3 + strlen(self::ORIGIN), strlen($report['message'])); + self::assertSame(1, $report['values']['exitCode']); + self::assertStringEndsWith('xend', $report['values']['stdout']); + self::assertSame(FunctionError::SHORTENED_LENGTH + 3, strlen($report['values']['stdout'])); + } + + #[Test] + public function itDropsTheValuesWhenShorteningIsNotEnough(): void + { + $values = array_fill(0, 32, str_repeat('x', FunctionError::SHORTENED_LENGTH)); + $error = self::queryError('failed', ['many' => $values]); + + self::assertSame('{"message":"failed","values":{}}', FunctionError::fileReport($error)); + } + + #[Test] + public function itWritesTheFileAndAShortTraceOfTheModulesFrames(): void + { + $error = self::caught(self::failNatively(...)); + $path = $this->tempFile(); + + [$file, $logs] = $this->report($error, $path); + + self::assertSame('{"message":"function failed natively","values":{}}', $file); + $trace = $error->getTrace(); + self::assertSame( + sprintf( + "RuntimeException: function failed natively in %s:%d\nStack trace:\n" + . "#0 %s(%d): %s::failNatively()\n#1 %s(%d): %s::caught()\n", + __FILE__, + $error->getLine(), + __FILE__, + $trace[0]['line'] ?? 0, + self::class, + __FILE__, + $trace[1]['line'] ?? 0, + self::class, + ), + $logs, + ); + self::assertStringNotContainsString('phpunit', $logs); + self::assertStringNotContainsString(FunctionError::MARKER, $logs); + } + + #[Test] + public function itLogsNothingForAnApiErrorWhoseOriginTheEngineShows(): void + { + $path = $this->tempFile(); + + [$file, $logs] = $this->report(self::queryError('exit code: 1' . self::ORIGIN, self::EXEC_ERROR), $path); + + self::assertStringStartsWith('{"message":"exit code: 1' . self::ORIGIN . '"', $file); + self::assertSame('', $logs); + } + + #[Test] + public function itLogsAnApiErrorWithoutAnOrigin(): void + { + $path = $this->tempFile(); + + $error = self::queryError('invalid ID'); + $line = __LINE__ - 1; + + [, $logs] = $this->report($error, $path); + + self::assertSame( + "GraphQL\\Exception\\QueryError: invalid ID in " . __FILE__ . ':' . $error->getLine() . "\n" + . "Stack trace:\n#0 " . __FILE__ . "($line): " . self::class . "::queryError()\n", + $logs, + ); + } + + #[Test] + public function itLogsAWrappedErrorAfterWhatItWraps(): void + { + $inner = self::queryError('exit code: 1' . self::ORIGIN, self::EXEC_ERROR); + $error = new RuntimeException('ran a failing command: ' . $inner->getMessage(), previous: $inner); + $line = __LINE__ - 1; + + $logs = $this->functionError()->shortTrace($error); + + self::assertSame( + "GraphQL\\Exception\\QueryError: exit code: 1 in " . __FILE__ . ':' . $inner->getLine() . "\n" + . "Stack trace:\n#0 " . __FILE__ . '(' . ($line - 1) . '): ' . self::class . "::queryError()\n" + . "\nNext RuntimeException: ran a failing command: exit code: 1 in " . __FILE__ . ":$line\n", + $logs, + ); + } + + #[Test] + public function itLogsAParseErrorAsPhpDoes(): void + { + $source = $this->tempFile(); + file_put_contents($source, "functionError()->shortTrace($error), + ); + } + + #[Test] + public function itFallsBackToTheMarker(): void + { + [, $logs] = $this->report(new RuntimeException("two\nlines" . self::ORIGIN), null); + + $lines = explode("\n", rtrim($logs, "\n")); + self::assertStringStartsWith('dagger-module: RuntimeException: two', $logs); + self::assertSame(FunctionError::MARKER . '"two\nlines' . self::ORIGIN . '"', end($lines)); + } + + #[Test] + public function itFallsBackToTheMarkerWhenTheFileCannotBeWritten(): void + { + [, $logs] = $this->report(new RuntimeException('failed'), '/nonexistent/dir/error.json'); + + self::assertStringEndsWith(FunctionError::MARKER . "\"failed\"\n", $logs); + } +} From 2d2657f81ef2cccf160b59a1e827acf577a83507 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 09:41:32 +0000 Subject: [PATCH 3/6] module: keep error output on older engines From review. On an engine without the function error file, which is every released one: - the marker fallback writes a failed exec's stdout and stderr, which the error is or wraps, to the dispatcher's own streams again, as before; - a dispatcher exec that failed without a marker, such as a function that exits, raises the exec's stderr as before, unless the engine marks the module process (moduleProcess), which then shows the exec's logs and exit code with its error; - so does a failed Composer install, which such an engine doesn't build as prebuild ahead of the call. A fatal error (exhausted memory, a class that can't be declared) ends the script with no Throwable to catch: a shutdown function now reports it in the file, or with the marker. PHP shows the error itself. Signed-off-by: Alex Suraci --- sdk/bin/dagger-module | 22 +++++- sdk/src/Module/DangEntrypointRenderer.php | 25 ++++++- sdk/src/Module/FunctionError.php | 48 +++++++++++- .../Module/DangEntrypointRendererTest.php | 21 +++++- sdk/tests/Unit/Module/FunctionErrorTest.php | 73 +++++++++++++++++++ 5 files changed, 175 insertions(+), 14 deletions(-) diff --git a/sdk/bin/dagger-module b/sdk/bin/dagger-module index 7d7eeb6..48ec0c4 100755 --- a/sdk/bin/dagger-module +++ b/sdk/bin/dagger-module @@ -38,6 +38,18 @@ function required(array $options, string $name): string return $options[$name] ?? fail(USAGE, 2); } +function functionError(): FunctionError +{ + return FunctionError::forModule(dirname(__DIR__), (string) getcwd()); +} + +function functionErrorPath(): ?string +{ + $path = getenv(FunctionError::PATH_ENV); + + return $path === false ? null : $path; +} + $autoload = getcwd() . '/vendor/autoload.php'; if (!is_file($autoload)) { fail("the module's dependencies are not installed: $autoload does not exist"); @@ -47,6 +59,12 @@ require $autoload; $mode = $argv[1] ?? ''; $options = options(array_slice($argv, 2)); +if ($mode === 'call') { + // A fatal error, such as exhausted memory or a class that can't be + // declared, ends the script with no Throwable to catch below. + register_shutdown_function(static fn() => functionError()->reportFatal(error_get_last(), functionErrorPath(), STDERR)); +} + try { switch ($mode) { case 'generate': @@ -77,9 +95,7 @@ try { if ($mode === 'call') { // A failed call exits 2, so that its exec isn't cached, and reports // the function's error to the engine; see FunctionError. - $path = getenv(FunctionError::PATH_ENV); - FunctionError::forModule(dirname(__DIR__), (string) getcwd()) - ->report($t, $path === false ? null : $path, STDERR); + functionError()->report($t, functionErrorPath(), STDERR, STDOUT); exit(2); } if (!$t instanceof QueryError) { diff --git a/sdk/src/Module/DangEntrypointRenderer.php b/sdk/src/Module/DangEntrypointRenderer.php index 09454f1..be0bfd2 100644 --- a/sdk/src/Module/DangEntrypointRenderer.php +++ b/sdk/src/Module/DangEntrypointRenderer.php @@ -310,8 +310,11 @@ private static function wrap(string $call, array $body): array fnArgs: fnArgs, }}) # A failed install stays out of the rescue below, so it fails the call - # with its own error. - let installed = runtime.sync + # with its own error. An engine that builds prebuild first fails the + # call before it gets here. + let installed = runtime.sync rescue { + err: GraphQLError => raiseWithStderr(err) + } let result = installed .withEnvVariable("DAGGER_CLIENT_VERSION", %clientVersion%) # The exec is cached on its own recipe, which holds neither the call's @@ -334,7 +337,7 @@ private static function wrap(string $call, array $body): array # the dispatcher'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 - # again. + # again, or, on an engine that marks no module process, its stderr. let raiseFunctionError(err: GraphQLError!): String! { let reported = ((JSON.decode(err.extensions) :: {{functionError: {{message: String, id: String}}}}).functionError != null) rescue false if (reported) { @@ -344,11 +347,25 @@ private static function wrap(string $call, array $body): array 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 + raiseWithStderr(err) } raise ((JSON.decode(lines.takeLast(1).join("").trimPrefix(marker)) :: String!) rescue err.message) } + # Raise a failed exec's error. An engine that marks the module process + # (the moduleProcess extension) shows an exec's logs with its error, so + # the error is raised as it is; an older engine shows only the exit + # code, so the end of the exec's stderr, which the engine caps at + # 100 KiB, is raised instead. + let raiseWithStderr(err: GraphQLError!): Container! { + let marked = ((JSON.decode(err.extensions) :: {{moduleProcess: Boolean}}).moduleProcess ?? false) rescue false + let stderr = ((JSON.decode(err.extensions) :: {{stderr: String}}).stderr ?? "") rescue "" + if (marked or stderr == "") { + raise err + } + raise stderr + } + let runtime: Container! { PhpModuleBuild(contextDir: currentModule.contextDirectory, subPath: currentModule.sourceSubpath).installed } diff --git a/sdk/src/Module/FunctionError.php b/sdk/src/Module/FunctionError.php index b08f791..2dacf8b 100644 --- a/sdk/src/Module/FunctionError.php +++ b/sdk/src/Module/FunctionError.php @@ -5,6 +5,7 @@ namespace Dagger\Module; use CompileError; +use ErrorException; use GraphQL\Exception\QueryError; use JsonException; use ParseError; @@ -50,6 +51,9 @@ /** An origin an error's message names: the span of the call the engine reports it from. */ public const ORIGIN = '/\s*\[traceparent:[0-9a-f]{32}-[0-9a-f]{16}\]/'; + /** The errors that end a PHP script without a Throwable to catch. */ + public const FATAL_ERRORS = E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR; + private const JSON_FLAGS = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE; @@ -83,11 +87,15 @@ public static function forModule(string $sdkRoot, string $moduleRoot): self /** * Report $error: in the file at $path when there is one and it can be - * written, else with the marker. Diagnostics go to $stderr. + * written, else with the marker. Diagnostics go to $stderr. Without the + * file, the output of a failed exec the error is or wraps goes to $stdout + * and $stderr first, as an engine that reads no file shows no exec's + * logs with its error. * * @param resource $stderr + * @param ?resource $stdout */ - public function report(Throwable $error, ?string $path, $stderr): void + public function report(Throwable $error, ?string $path, $stderr, $stdout = null): void { if ($path !== null && $path !== '' && self::writeFile($path, $error)) { if (!self::hasOrigin($error)) { @@ -96,8 +104,42 @@ public function report(Throwable $error, ?string $path, $stderr): void return; } + $values = self::values($error); + if ($stdout !== null && is_string($values['stdout'] ?? null)) { + fwrite($stdout, $values['stdout']); + } fwrite($stderr, sprintf("dagger-module: %s\n", $error)); - fwrite($stderr, self::MARKER . json_encode(self::truncate(self::messageOf($error)), self::JSON_FLAGS) . "\n"); + if (is_string($values['stderr'] ?? null) && $values['stderr'] !== '') { + fwrite($stderr, rtrim($values['stderr'], "\n") . "\n"); + } + self::writeMarker($stderr, self::messageOf($error)); + } + + /** + * Report a fatal error, which ends the script without a Throwable to + * catch, as error_get_last() returns it, from a shutdown function. PHP + * has shown it already, so it is only reported, in the file at $path or + * else with the marker. Anything other than a fatal error is ignored. + * + * @param ?array{type: int, message: string, file: string, line: int} $error + * @param resource $stderr + */ + public function reportFatal(?array $error, ?string $path, $stderr): void + { + if ($error === null || ($error['type'] & self::FATAL_ERRORS) === 0) { + return; + } + $fatal = new ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']); + if ($path !== null && $path !== '' && self::writeFile($path, $fatal)) { + return; + } + self::writeMarker($stderr, self::messageOf($fatal)); + } + + /** @param resource $stderr */ + private static function writeMarker($stderr, string $message): void + { + fwrite($stderr, self::MARKER . json_encode(self::truncate($message), self::JSON_FLAGS) . "\n"); } /** diff --git a/sdk/tests/Unit/Module/DangEntrypointRendererTest.php b/sdk/tests/Unit/Module/DangEntrypointRendererTest.php index eeb1be0..0e5d490 100644 --- a/sdk/tests/Unit/Module/DangEntrypointRendererTest.php +++ b/sdk/tests/Unit/Module/DangEntrypointRendererTest.php @@ -250,15 +250,17 @@ public function itRendersTheCallContract(): void self::assertStringContainsString('.contents rescue {', $main); self::assertStringContainsString('err: GraphQLError => raiseFunctionError(err)', $main); self::assertStringContainsString( - " let installed = runtime.sync\n let result = installed\n", + " let installed = runtime.sync rescue {\n" + . " err: GraphQLError => raiseWithStderr(err)\n" + . " }\n" + . " let result = installed\n", $main, - 'a failed install stays out of the rescue', + 'a failed install stays out of the function error rescue', ); self::assertStringContainsString( "pub prebuild: File! {\n runtime.file(\"vendor/autoload.php\")\n }", $main, ); - self::assertStringNotContainsString('raise stderr', $main); self::assertStringContainsString( 'PhpModuleBuild(contextDir: currentModule.contextDirectory, subPath: currentModule.sourceSubpath).installed', $main, @@ -283,8 +285,19 @@ public function itRaisesTheFunctionError(): void $main, ); self::assertStringContainsString( - 'raise ((JSON.decode(lines.takeLast(1).join("").trimPrefix(marker)) :: String!) rescue err.message)', + " if (lines.isEmpty) {\n raiseWithStderr(err)\n }\n" + . ' raise ((JSON.decode(lines.takeLast(1).join("").trimPrefix(marker)) :: String!) rescue err.message)', + $main, + ); + self::assertStringContainsString( + "let marked = ((JSON.decode(err.extensions) :: {{moduleProcess: Boolean}}).moduleProcess ?? false) rescue false\n" + . " let stderr = ((JSON.decode(err.extensions) :: {{stderr: String}}).stderr ?? \"\") rescue \"\"\n" + . " if (marked or stderr == \"\") {\n" + . " raise err\n" + . " }\n" + . " raise stderr\n", $main, + 'an engine that marks no module process gets the exec stderr, as before', ); } diff --git a/sdk/tests/Unit/Module/FunctionErrorTest.php b/sdk/tests/Unit/Module/FunctionErrorTest.php index dafd99e..00b10b5 100644 --- a/sdk/tests/Unit/Module/FunctionErrorTest.php +++ b/sdk/tests/Unit/Module/FunctionErrorTest.php @@ -264,6 +264,79 @@ public function itFallsBackToTheMarker(): void self::assertSame(FunctionError::MARKER . '"two\nlines' . self::ORIGIN . '"', end($lines)); } + /** + * An engine that reads no file shows no exec's logs with its error, so + * the output of the failed exec goes to the dispatcher's own streams, as + * before the file. + */ + #[Test] + public function itFallsBackWithTheOutputOfAFailedExec(): void + { + $inner = self::queryError('exit code: 1' . self::ORIGIN, self::EXEC_ERROR); + $error = new RuntimeException('ran a failing command: ' . $inner->getMessage(), previous: $inner); + $stdout = fopen('php://memory', 'w+'); + $stderr = fopen('php://memory', 'w+'); + self::assertNotFalse($stdout); + self::assertNotFalse($stderr); + + $this->functionError()->report($error, null, $stderr, $stdout); + + rewind($stdout); + rewind($stderr); + self::assertSame("exec stdout\n", stream_get_contents($stdout)); + self::assertStringEndsWith( + "exec stderr\n" . FunctionError::MARKER . '"ran a failing command: exit code: 1' . self::ORIGIN . "\"\n", + (string) stream_get_contents($stderr), + ); + } + + #[Test] + public function itReportsAFatalError(): void + { + $path = $this->tempFile(); + $stderr = fopen('php://memory', 'w+'); + self::assertNotFalse($stderr); + $fatal = ['type' => E_ERROR, 'message' => 'Allowed memory size exhausted', 'file' => __FILE__, 'line' => 1]; + + $this->functionError()->reportFatal($fatal, $path, $stderr); + + self::assertSame('{"message":"Allowed memory size exhausted","values":{}}', file_get_contents($path)); + rewind($stderr); + self::assertSame('', stream_get_contents($stderr), 'PHP shows a fatal error itself'); + } + + #[Test] + public function itReportsAFatalErrorWithTheMarker(): void + { + $stderr = fopen('php://memory', 'w+'); + self::assertNotFalse($stderr); + $fatal = ['type' => E_COMPILE_ERROR, 'message' => 'Cannot redeclare f()', 'file' => __FILE__, 'line' => 1]; + + $this->functionError()->reportFatal($fatal, null, $stderr); + + rewind($stderr); + self::assertSame(FunctionError::MARKER . "\"Cannot redeclare f()\"\n", stream_get_contents($stderr)); + } + + #[Test] + public function itIgnoresAnErrorThatIsNotFatal(): void + { + $path = $this->tempFile(); + $stderr = fopen('php://memory', 'w+'); + self::assertNotFalse($stderr); + + $this->functionError()->reportFatal(null, $path, $stderr); + $this->functionError()->reportFatal( + ['type' => E_WARNING, 'message' => 'mkdir(): File exists', 'file' => __FILE__, 'line' => 1], + $path, + $stderr, + ); + + self::assertSame('', file_get_contents($path)); + rewind($stderr); + self::assertSame('', stream_get_contents($stderr)); + } + #[Test] public function itFallsBackToTheMarkerWhenTheFileCannotBeWritten(): void { From cc75f2c6da2007d49a35fca5202090c4e7d3c18c Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 09:57:56 +0000 Subject: [PATCH 4/6] module: report exhausted memory, keep the cwd From review. The shutdown handler that reports a fatal error had no memory left after the commonest one, exhausted memory: autoloading FunctionError there failed a second time. FunctionError is now made, and the error path read, before the function runs, and the handler frees 256 KiB it reserved first. Taking the module root up front also keeps a function's chdir() from moving where vendor/ is looked for. Signed-off-by: Alex Suraci --- sdk/bin/dagger-module | 20 ++++-------- sdk/src/Module/FunctionError.php | 19 +++++++++++ sdk/tests/Unit/Module/FunctionErrorTest.php | 35 +++++++++++++++++++++ 3 files changed, 60 insertions(+), 14 deletions(-) diff --git a/sdk/bin/dagger-module b/sdk/bin/dagger-module index 48ec0c4..a35d44d 100755 --- a/sdk/bin/dagger-module +++ b/sdk/bin/dagger-module @@ -38,18 +38,6 @@ function required(array $options, string $name): string return $options[$name] ?? fail(USAGE, 2); } -function functionError(): FunctionError -{ - return FunctionError::forModule(dirname(__DIR__), (string) getcwd()); -} - -function functionErrorPath(): ?string -{ - $path = getenv(FunctionError::PATH_ENV); - - return $path === false ? null : $path; -} - $autoload = getcwd() . '/vendor/autoload.php'; if (!is_file($autoload)) { fail("the module's dependencies are not installed: $autoload does not exist"); @@ -59,10 +47,14 @@ require $autoload; $mode = $argv[1] ?? ''; $options = options(array_slice($argv, 2)); +// Made before the function runs, which may change the working directory. +$functionError = FunctionError::forModule(dirname(__DIR__), (string) getcwd()); +$functionErrorPath = getenv(FunctionError::PATH_ENV); +$functionErrorPath = $functionErrorPath === false ? null : $functionErrorPath; if ($mode === 'call') { // A fatal error, such as exhausted memory or a class that can't be // declared, ends the script with no Throwable to catch below. - register_shutdown_function(static fn() => functionError()->reportFatal(error_get_last(), functionErrorPath(), STDERR)); + $functionError->reportFatalErrors($functionErrorPath, STDERR); } try { @@ -95,7 +87,7 @@ try { if ($mode === 'call') { // A failed call exits 2, so that its exec isn't cached, and reports // the function's error to the engine; see FunctionError. - functionError()->report($t, functionErrorPath(), STDERR, STDOUT); + $functionError->report($t, $functionErrorPath, STDERR, STDOUT); exit(2); } if (!$t instanceof QueryError) { diff --git a/sdk/src/Module/FunctionError.php b/sdk/src/Module/FunctionError.php index 2dacf8b..dc22c9e 100644 --- a/sdk/src/Module/FunctionError.php +++ b/sdk/src/Module/FunctionError.php @@ -54,6 +54,9 @@ /** The errors that end a PHP script without a Throwable to catch. */ public const FATAL_ERRORS = E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR; + /** The memory reportFatalErrors keeps for the report of exhausted memory. */ + private const FATAL_RESERVE = 256 * 1024; + private const JSON_FLAGS = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE; @@ -136,6 +139,22 @@ public function reportFatal(?array $error, ?string $path, $stderr): void self::writeMarker($stderr, self::messageOf($fatal)); } + /** + * Report the fatal error that ends this script, if one does, from a + * shutdown function (see reportFatal). The memory it reserves is freed + * first, so that a script that exhausted its memory can still report it. + * + * @param resource $stderr + */ + public function reportFatalErrors(?string $path, $stderr): void + { + $reserved = str_repeat("\0", self::FATAL_RESERVE); + register_shutdown_function(function () use (&$reserved, $path, $stderr): void { + $reserved = null; + $this->reportFatal(error_get_last(), $path, $stderr); + }); + } + /** @param resource $stderr */ private static function writeMarker($stderr, string $message): void { diff --git a/sdk/tests/Unit/Module/FunctionErrorTest.php b/sdk/tests/Unit/Module/FunctionErrorTest.php index 00b10b5..f4d3334 100644 --- a/sdk/tests/Unit/Module/FunctionErrorTest.php +++ b/sdk/tests/Unit/Module/FunctionErrorTest.php @@ -318,6 +318,41 @@ public function itReportsAFatalErrorWithTheMarker(): void self::assertSame(FunctionError::MARKER . "\"Cannot redeclare f()\"\n", stream_get_contents($stderr)); } + /** + * The commonest fatal error, exhausted memory, leaves the shutdown + * function no memory of its own but what reportFatalErrors reserved. + */ + #[Test] + public function itReportsExhaustedMemory(): void + { + $path = $this->tempFile(); + $sdk = dirname(__DIR__, 3); + $script = sprintf( + 'require %s; Dagger\Module\FunctionError::forModule(%s, %s)->reportFatalErrors(%s, STDERR);' + . ' $kept = []; while (true) { $kept[] = new stdClass(); }', + var_export("$sdk/vendor/autoload.php", true), + var_export("$sdk/src", true), + var_export($sdk, true), + var_export($path, true), + ); + $process = proc_open( + [PHP_BINARY, '-d', 'memory_limit=32M', '-d', 'display_errors=0', '-d', 'log_errors=0', '-r', $script], + [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes, + ); + self::assertIsResource($process); + $output = stream_get_contents($pipes[1]) . stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + + self::assertSame(255, proc_close($process), $output); + self::assertStringStartsWith( + '{"message":"Allowed memory size of 33554432 bytes exhausted', + (string) file_get_contents($path), + $output, + ); + } + #[Test] public function itIgnoresAnErrorThatIsNotFatal(): void { From ad9445a92c36e35a3d913c570239f9ed7b7fd257 Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Sun, 22 Nov 2026 15:02:52 +0000 Subject: [PATCH 5/6] module: test the memory reserve by recursion From review. Exhausting memory with a growing array leaves the shutdown function enough memory without the reserve, so that test passed without it. Exhausting it by deep recursion does not: that case fails with a reserve of 0, so it now covers the reserve, beside the array case. Signed-off-by: Alex Suraci --- sdk/tests/Unit/Module/FunctionErrorTest.php | 24 ++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/sdk/tests/Unit/Module/FunctionErrorTest.php b/sdk/tests/Unit/Module/FunctionErrorTest.php index f4d3334..ec2c2a3 100644 --- a/sdk/tests/Unit/Module/FunctionErrorTest.php +++ b/sdk/tests/Unit/Module/FunctionErrorTest.php @@ -8,6 +8,7 @@ use GraphQL\Exception\QueryError; use ParseError; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -318,22 +319,35 @@ public function itReportsAFatalErrorWithTheMarker(): void self::assertSame(FunctionError::MARKER . "\"Cannot redeclare f()\"\n", stream_get_contents($stderr)); } + /** @return array */ + public static function memoryExhaustions(): array + { + return [ + 'by a growing array' => ['$kept = []; while (true) { $kept[] = new stdClass(); }'], + // Leaves the shutdown function no memory of its own but what + // reportFatalErrors reserved: without it, nothing is reported. + 'by deep recursion' => [ + 'function r($n) { $a = [$n, new stdClass()]; return r($n + 1) + count($a); } r(0);', + ], + ]; + } + /** - * The commonest fatal error, exhausted memory, leaves the shutdown - * function no memory of its own but what reportFatalErrors reserved. + * The commonest fatal error, exhausted memory, is reported too. */ #[Test] - public function itReportsExhaustedMemory(): void + #[DataProvider('memoryExhaustions')] + public function itReportsExhaustedMemory(string $workload): void { $path = $this->tempFile(); $sdk = dirname(__DIR__, 3); $script = sprintf( - 'require %s; Dagger\Module\FunctionError::forModule(%s, %s)->reportFatalErrors(%s, STDERR);' - . ' $kept = []; while (true) { $kept[] = new stdClass(); }', + 'require %s; Dagger\Module\FunctionError::forModule(%s, %s)->reportFatalErrors(%s, STDERR); %s', var_export("$sdk/vendor/autoload.php", true), var_export("$sdk/src", true), var_export($sdk, true), var_export($path, true), + $workload, ); $process = proc_open( [PHP_BINARY, '-d', 'memory_limit=32M', '-d', 'display_errors=0', '-d', 'log_errors=0', '-r', $script], From 5771a9b4bdd48fa329a40cd57436e3854db975cd Mon Sep 17 00:00:00 2001 From: Alex Suraci Date: Mon, 23 Nov 2026 15:47:55 +0000 Subject: [PATCH 6/6] module: the engine reads only JSON reports The engine no longer takes a report with an empty message for plain text: it reads only a JSON report with a message or an Error ID, and rejects any other as invalid (dagger/dagger#15249). Comments only. Signed-off-by: Alex Suraci --- sdk/src/Module/FunctionError.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sdk/src/Module/FunctionError.php b/sdk/src/Module/FunctionError.php index dc22c9e..7494e92 100644 --- a/sdk/src/Module/FunctionError.php +++ b/sdk/src/Module/FunctionError.php @@ -280,8 +280,9 @@ private static function writeFile(string $path, Throwable $error): bool } /** - * The error's message, or its class when it has none: the engine takes - * a report with an empty message for plain text. + * The error's message, or its class when it has none: the engine reads + * only a JSON report with a message, and rejects one with an empty + * message as invalid. */ private static function messageOf(Throwable $error): string {