Skip to content

Effect.catch, Effect.result and the other typed-error operators discard a defect that sits beside the typed failure (e.g. a finalizer that dies) #9425

Closed

Description

@nick-inkeep

What version of Effect is running?

[email protected] on Node 26.11.1. The code is unchanged on main.

What steps can reproduce the bug?

When a typed failure and a defect end up in the same Cause, the typed-error operators pass the Fail to their handler and discard the Die. That happens when an effect fails and its finalizer or release then dies, or when a concurrent sibling's finalizer dies as Effect.all interrupts it. Nothing re-raises or logs the defect, so a crash in cleanup code disappears.

import { Effect, Exit } from "effect"

const show = (exit: Exit.Exit<unknown, unknown>) =>
  Exit.isSuccess(exit) ? `Success(${exit.value})` : exit.cause.reasons.map((r) => r._tag).join(" + ")

// A typed failure whose finalizer dies
const sequential = Effect.fail("typed").pipe(Effect.ensuring(Effect.die("finalizer defect")))
// A typed failure while a concurrent sibling's finalizer dies on interruption
const parallel = Effect.all([
  Effect.never.pipe(Effect.ensuring(Effect.die("finalizer defect"))),
  Effect.fail("typed")
], { concurrency: "unbounded" })

const sources: ReadonlyArray<Effect.Effect<unknown, string>> = [sequential, parallel]
for (const self of sources) {
  console.log(show(await Effect.runPromiseExit(self)))
  console.log(show(await Effect.runPromiseExit(Effect.catch(self, () => Effect.succeed("recovered")))))
  console.log(show(await Effect.runPromiseExit(Effect.result(self))))
  console.log(show(await Effect.runPromiseExit(Effect.ignore(self))))
  console.log(show(await Effect.runPromiseExit(Effect.mapError(self, () => "mapped"))))
}

For each source:

Fail + Die
Success(recovered)
Success(failure("typed"))
Success(undefined)
Fail

catchTag, catchTags, catchIf, catchFilter, orElseSucceed, option, match, matchEffect, firstSuccessOf, eventually, isSuccess, isFailure and Stream.catch lose the defect the same way, and orDie replaces it with Die("typed"). Of the operators tried, only Effect.ignore({ log: true }) reports it. An Interrupt beside a Fail is dropped the same way.

These cases, added to packages/effect/test/Effect.test.ts, fail on main for all nine operators. The source check and each operator's typed-failure-only control pass:

describe("typed failure beside a defect", () => {
  const failureWithDefect = Effect.fail("error").pipe(Effect.ensuring(Effect.die("finalizer defect")))

  const operators: ReadonlyArray<{
    readonly name: string
    readonly apply: (self: Effect.Effect<never, string>) => Effect.Effect<unknown, unknown>
    readonly onTypedFailure: Exit.Exit<unknown, unknown>
  }> = [
    {
      name: "catch",
      apply: (self) => Effect.catch(self, () => Effect.succeed("recovered")),
      onTypedFailure: Exit.succeed("recovered")
    },
    {
      name: "catchIf",
      apply: (self) => Effect.catchIf(self, (error) => error === "error", () => Effect.succeed("recovered")),
      onTypedFailure: Exit.succeed("recovered")
    },
    {
      name: "orElseSucceed",
      apply: (self) => Effect.orElseSucceed(self, () => "fallback"),
      onTypedFailure: Exit.succeed("fallback")
    },
    { name: "result", apply: (self) => Effect.result(self), onTypedFailure: Exit.succeed(Result.fail("error")) },
    { name: "option", apply: (self) => Effect.option(self), onTypedFailure: Exit.succeed(Option.none()) },
    { name: "ignore", apply: (self) => Effect.ignore(self), onTypedFailure: Exit.void },
    {
      name: "match",
      apply: (self) => Effect.match(self, { onFailure: () => "failure", onSuccess: () => "success" }),
      onTypedFailure: Exit.succeed("failure")
    },
    { name: "mapError", apply: (self) => Effect.mapError(self, () => "mapped"), onTypedFailure: Exit.fail("mapped") },
    { name: "isFailure", apply: (self) => Effect.isFailure(self), onTypedFailure: Exit.succeed(true) }
  ]

  it.effect("the source fails with both the typed failure and the defect", () =>
    Effect.gen(function*() {
      const exit = yield* Effect.exit(failureWithDefect)
      assert.deepStrictEqual(exit, Exit.failCause(Cause.combine(Cause.fail("error"), Cause.die("finalizer defect"))))
    }))

  for (const { apply, name, onTypedFailure } of operators) {
    it.effect(`${name} handles a typed failure alone`, () =>
      Effect.gen(function*() {
        const exit = yield* Effect.exit(apply(Effect.fail("error")))
        assert.deepStrictEqual(exit, onTypedFailure)
      }))

    it.effect(`${name} does not discard the defect`, () =>
      Effect.gen(function*() {
        const exit = yield* Effect.exit(apply(failureWithDefect))
        assert.isTrue(
          Exit.isFailure(exit) &&
            exit.cause.reasons.some((reason) => reason._tag === "Die" && reason.defect === "finalizer defect")
        )
      }))
  }
})

What is the expected behavior?

The handler deals with the typed failure, and the defect still fails the effect, as the docs say:

  • result: "Defects and interruptions are not captured inside the Result and still fail the effect" (Effect.ts#L2305-L2307); option says the same (#L2349-L2351).
  • catch: "while unrecoverable defects remain defects" and "It will not recover from unrecoverable defects" (#L2740-L2753).
  • catchIf: "Defects and interrupts are not caught" (#L3407-L3408); orElseSucceed: "Defects and interruptions are not recovered by this operator" (#L4539); isSuccess: "defects still fail the effect" (#L5832-L5833).
  • The v4 guide: Effect.ignore "Defects and interruptions are preserved" (matching.mdx#L70), and "Fallback operators recover from typed failures. Defects and interruptions remain unchanged" (fallback.mdx#L8).

If dropping the defect is intended, these lines need to say so.

What do you see instead?

The effect succeeds with the handler's value, and the Die is gone from its Cause. With mapError the effect still fails, but only with the mapped error.

Additional information

All of these take the first Fail and drop the rest of the Cause:

v3 kept the defect for most of these. On 3.22.3, catchAll, either, option, ignore, match, orElseSucceed and orDie do not call the handler when the Cause holds a defect; matchEffect re-fails with each typed failure turned into a defect, beside the original defect (internal/core.ts at 3.22.3, #L902-L912). The migration guide lists catchAll → catch (migration/error-handling.md#L11) as a rename, and maps either → result (migration/annotations/effect__Effect.yaml#L152-L154); neither notes this change.

retry and repeat already pass a Cause through unless every reason is a Fail (findErrorOnly, internal/schedule.ts#L13-L14, #8799), and Config.orElse leaves causes with defects unrecovered (#8808). #9368 is the mirror case for catchDefect. #7125 added failing tests for result and option in this case and was closed without a fix or a comment. Most of these operators' error type no longer includes E, so keeping the defect means re-failing with the Die and Interrupt reasons without the handled Fail, as #8652 does when it skips handlers.

Activity

  1. self-assigned this
    on Oct 16, 2026
  2. effect-bot commented on Oct 17, 2026

    @effect-bot
    Contributor

    PR #9433 now addresses the defect half of this issue, with a narrower design than the earlier versions of that PR.

    When the runtime combines a typed failure with a defect, the typed failure now becomes a defect, and the original error stays first: Fail(e) + Die(d) becomes Die(e) + Die(d). The runtime does this at three places:

    • finalizers: ensuring, onExit, acquireRelease and scope close
    • concurrent forEach/Effect.all
    • raceAll when every racer fails

    As a result, catch, result, option, ignore, match, mapError, orDie, catchTag/catchIf and Stream.catch can no longer swallow a crashing finalizer or a dying concurrent sibling. Both reproductions from the report now propagate the defect. The original typed error is still reported, but as a defect, so catchDefect/sandbox will see it and catchTag/catchIf will not.

    Deliberately not changed in that PR:

    • Interruption. A typed failure that comes only with an interruption, and no defect, is still recoverable by typed-error operators, as before and as in v3. This part of the report is not fixed by Give finalizer and concurrent defects precedence over typed failures #9433.
    • Causes combined elsewhere. This includes the public Cause.combine, hand-built Effect.failCause(Cause.combine(fail, die)) and library code that combines causes itself. Typed-error operators can still recover these.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions