unthrown icon indicating copy to clipboard operation
unthrown copied to clipboard

A saga combinator for `AsyncResult`: steps carrying compensating undos, unwound LIFO on `Err`

Open btravers opened this issue 3 months ago • 1 comments

unthrown has DoAsync().bind() for a sequence where a later step needs an earlier step's value. It has nothing for a sequence where a later step's failure must undo the earlier ones.

That shape is the saga, and it is hand-written wherever it appears. From btravstack/start's examples/order-temporal-worker/src/workflows.ts:

.flatTap(() =>
  arrangeShipping(order).flatMapErrCases((matcher) =>
    matcher
      .with({ errorName: "ShippingUnavailable" }, (error) =>
        releaseStock(order)
          .flatMap(() => cancelPlacement(order))
          .flatMap(() => ErrAsync(errors.ShippingUnavailable({ id: error.data.id }))),
      )
      // …
  ),
)

Two traps live in that spelling, and both are the kind a combinator gets right once:

  • Ordering. The undos must run in reverse of the steps that earned them. Nothing checks it, and getting it backwards is silent.
  • Eagerness. An AsyncResult starts on construction, so each undo has to be built inside the failure branch. Written the readable way — one const per undo — it is unthrown/no-async-result-race (#247).

Shape

SagaAsync()
  .step(() => place(order),        () => cancelPlacement(order))
  .step(() => reserveStock(order), () => releaseStock(order))
  .step(() => arrangeShipping(order))
  .run()

step(run, undo?) — run is a thunk returning AsyncResult<T, E>; undo an optional thunk returning AsyncResult<unknown, never>. Compensation must not invent new ways to fail, and that is already how the motivating ports are typed: StockService.release is AsyncResult<void, never>.

run() answers the last step's value on success. On the first Err it runs the recorded undos LIFO and returns that Err unchanged — a saga reports the failure that caused the walk-back, never the walk-back itself.

Thunks rather than values, for the eagerness reason above: an AsyncResult parameter would start every step at construction, so the combinator would be a race generator.

Open questions:

  • Whether a step sees earlier steps' values (the DoAsync accumulating scope) or stays positional. Positional covers both known call sites.
  • Whether undo receives the failing error. Needed if a caller wants to decide per-failure whether to compensate — see the policy half, linked below.

Constraint: pure control flow

The first consumer runs inside Temporal's deterministic workflow sandbox, so the combinator must add no timers, no Date.now, no randomness — sequencing only. Low risk: flatTap and mapErrCases already run there today.

A second consumer is already written down

btravstack/start's spec names the outbox plus a saga as its answer for cross-store atomicity — in the application layer, with no Temporal anywhere near it. That one would take this directly.

Prior art

Effect's Workflow.withCompensation unwinds LIFO in the same way. Its default fires on any failure, which is the part deliberately not copied — see btravstack/temporal-contract#413.

btravers avatar Sep 01 '26 00:09 btravers

I built the proposed API against packages/core/src and drove the two real workflows through it. Three findings, verified rather than argued.

1. The shape can't express chargeOrder — which lives in the file this issue quotes

Positional covers both known call sites.

It doesn't. fulfillOrder compiles positionally. chargeOrder, in the same examples/order-temporal-worker/src/workflows.ts, does not — step 2 and step 1's undo both need step 1's value:

SagaAsync()
  .step(
    () => authorizePayment(order),
    () => refundPayment({ authorizationId: authorized.authorizationId }), // ✗ unbound
  )
  .step(() => capturePayment({ authorizationId: authorized.authorizationId })) // ✗ unbound
  .run()

Today that value comes from the enclosing .flatTap((authorized) => …). Under a positional saga there is no binding for it. Both @ts-expect-errors were consumed under tsc — the errors are real.

So the scope has to accumulate like DoAsync().bind(). Which makes this a compensating Do, not a new sequencing concept — and that is a different, larger design than the one specced here.

2. undo's error parameter cannot be soundly typed — and it is not optional

An undo fires on failures from steps declared after it, so the error union known at .step() time is the wrong one. An infallible step's undo types as (error: never) and receives a real error at runtime:

SagaAsync()
  .step(place, (error) => {           // place: AsyncResult<void, never>
    const proof: never = error;       // compiles
    return OkAsync();
  })
  .step(shipping)                     // shipping: AsyncResult<void, Boom>
  .run()
step-1 undo received: Boom
saga result tag: Err error: Boom

The issue files this as open ("whether undo receives the failing error"). btravstack/temporal-contract#413 closes it: exempting ACTIVITY_ERROR_TAG / ACTIVITY_CANCELLED_ERROR_TAG requires each undo to see the error. So the parameter is mandatory and its type is unsolved — either unknown, which puts an untyped error in front of domain code against Thesis #1, or E declared up front, which kills the fluent builder.

3. The second consumer isn't written down

btravstack/start's CLAUDE.md:245 names outbox + saga as its cross-store atomicity strategy. There is no saga call site there. Real consumers today: fulfillOrder and chargeOrder, one file.

Two more gaps

  • undo: () => AsyncResult<unknown, never> — never means the error channel is empty, not that the undo is total (the documented recoverErrCases invariant). What a compensation Defect does to the Err being walked back is unspecified. The library already has a rule for this shape: a throw in tapErrCases aggregates rather than destroying the original failure.
  • run() unwinding on the first Err is Effect's default — the one this issue says is "deliberately not copied". Everything that makes it correct lives in #413.

Recommendation: close, and build it in #413

#413 has to be written regardless — which failures compensate is Temporal's business, and that wrapper owns the step list. Once it does, the LIFO unwind it needs from unthrown is this, on today's public surface:

done.reduce((acc, s) => acc.flatMap(() => s.undo(error)), OkAsync())
    .flatMap(() => ErrAsync(error))   // `done` built by prepending

Three lines, no new core surface. And the parts the saga doesn't remove from fulfillOrder — the per-step mapErrCases re-minting against context.errors, the machinery-tag arm — are most of what's actually on screen.

Against "keep the surface small enough that the library can be done", core would be taking on an accumulating-scope orchestration builder with an unsolved type parameter to save one downstream package three lines.

btravers avatar Sep 01 '26 06:09 btravers