Skip to content

feat(v2): typed Step[I, O] built on Go 1.27 generic methods - #5

Merged
veggiemonk merged 1 commit into
mainfrom
feat/v2
Sep 21, 2026
Merged

veggiemonk merged 1 commit into
mainfrom
feat/v2

Conversation

@veggiemonk

Copy link
Copy Markdown
Owner

Why

v1 models a step as Step[T]: it reads a T and returns a T, so one type has to carry the whole pipeline. That single decision causes three defects. I reproduced each one against v1 before writing this, and each now has a regression test in v2.

1. Middleware collects a new layer on every run. Pipeline.Run and series.Run write to their own step slice while they run (workflow.go:46, workflow.go:281):

run 1 middleware invocations: 1
run 2 middleware invocations: 2
run 3 middleware invocations: 3

A Retry(3) becomes 9 attempts on the second run. Two concurrent runs also race.

2. Parallel + Merge drops a branch. Two branches each did Counter++ and appended a message:

parallel merge -> Counter=1 (expected 2), Msgs=[task1]

mergo does not overwrite a non-empty destination field. The second branch is lost in silence. This is the exact pattern in the current README.

3. A panic in a parallel branch crashes the caller. CapturePanic logs it and lets the goroutine return nil. errgroup sees success, resps[i] stays nil, and mergo then panics on the nil pointer:

panic: reflect: call of reflect.Value.Type on zero Value

One panic becomes two, and the second is not recovered.

These are not bugs in the implementation. They follow from the shape of Step[T], which forces a merge function, forces a deep copy, and gives no typed place to put a branch result.

What changed

A step now declares its own input type and its own output type. The compiler does the work that reflection did.

parse := workflow.Func("Parse", func(ctx context.Context, d Doc) (Tokens, error) { ... })
count := workflow.Pure("Count", func(t Tokens) int { return len(t) })

pipeline := parse.Then(count)          // Step[Doc, int]
batch    := workflow.Each(8, pipeline) // Step[[]Doc, []int]

Two constraints the compiler imposed

Step is a concrete struct, not an interface. Go 1.27 allows type parameters on a method only when the receiver is a concrete type:

interface method must have no type parameters

Generic methods are the whole point — they let a chain change type. Runner[I, O] stays a plain interface, for a type that carries state; wrap it with Of.

Each is a package-level function, not a method. A method returning Step[[]I,[]O] makes the compiler instantiate Step[[][]I,[][]O], and so on without end:

instantiation cycle: I instantiated as []I

The rule: a new type parameter on a method is fine, a type expression built from the receiver's own parameters is not.

How each defect becomes impossible

Defect Fix Test
Middleware re-wraps A step is a value; every method returns a new step and no method writes to its receiver. Middleware is applied once, at build time. TestMiddlewareIsAppliedOnce
Merge drops a branch The join function is typed; the compiler will not let a result go unused. TestParKeepsEveryResult
Panic crashes the caller Par, Fan and Each turn a branch panic into a *PanicError. TestParTurnsPanicIntoError

Also fixed

  • CircuitBreaker is an explicit value. v1 kept its state in the middleware closure, so every step the middleware wrapped shared one circuit without saying so. Covered by TestBreakersAreIndependentUnlessShared.
  • Timeout starts no goroutine. v1 raced one and leaked it. The step must honour the context, which is the only thing Go can actually guarantee.
  • Log never records the payload. v1 wrote fmt.Sprintf("%v", resp) of the whole struct, which can hold a secret and costs more than a short step.
  • Errors are joined, not dropped. Par, Fan and Each run every branch to the end and return every error with errors.Join. v1's errgroup returned the first one only.

Removed

mergo, google/uuid, x/sync, reflect, MergeRequest, Merge, MergeTransform, SafeCopy, DeepCopyInterface, StepValidator, SafeRun, and the four near-identical tree printers in Pipeline, series, parallel and selector.

v2 has no dependency outside the standard library.

Layout

v2 is a separate module in the v2/ subdirectory, the standard Go major-version layout. v1 keeps working and keeps its import path. v2/README.md holds a full migration table.

ci.yml now runs a matrix over both modules. Before this, CI ran at the repo root only and would not have tested v2 at all.

Verification

coverage: 98.2% of statements
go test -race -count=1 -shuffle=on        ok
go vet ./...                              clean
modernize -fix -diff ./...                prints nothing
go fix -diff ./...                        prints nothing
gofmt -l .                                prints nothing
golangci-lint run                         0 issues

Benchmarks, Apple M4 Max, Go 1.27. The sequential path allocates nothing:

BenchmarkRun-16                296803701     4.158 ns/op     0 B/op   0 allocs/op
BenchmarkThenChain-16           32746808    36.06  ns/op     0 B/op   0 allocs/op
BenchmarkSeq-16                 45185329    28.23  ns/op     0 B/op   0 allocs/op
BenchmarkPar-16                  1583120   758.9   ns/op   288 B/op   6 allocs/op
BenchmarkEach100-16                30480 39491     ns/op 20422 B/op 104 allocs/op
BenchmarkMiddlewareStack-16      4575774   262.6   ns/op   272 B/op   4 allocs/op

Deliberate trade-offs, open to discussion

  • Par, Fan and Each do not fail fast. Every branch runs to the end. This avoids confusing context canceled noise from a sibling, at the cost of work on a doomed run.
  • Timeout cannot abandon a step that ignores its context. Go cannot stop a goroutine from outside. v1 appeared to, but only by leaking the goroutine.
  • A pipeline is a tree, not a general graph. There is no node with two parents, and no durable state or resume. v2/README.md says so plainly under "What v2 is not".

Note on v1

This PR does not patch v1. The three defects above still affect anyone on the current release. Happy to follow up with a v1 patch branch.

🤖 Generated with Claude Code

v1 modelled a step as `Step[T]`: one type carried the whole pipeline.
That single decision caused three defects, each reproduced before this
change and each now covered by a regression test:

  - Pipeline.Run and series.Run rewrote their own step slice while they
    ran, so every run added another middleware layer (1, 2, then 3
    invocations of the same middleware).
  - Parallel + Merge dropped a branch. mergo refuses to overwrite a
    non-empty destination field, so two branches that each added 1
    produced 1, not 2.
  - A panic in a parallel branch was logged, the goroutine returned nil,
    and mergo then panicked on the nil pointer, crashing the caller.

v2 gives a step its own input type and its own output type. The compiler
now does the work that reflection did.

Step is a concrete struct, not an interface, because Go 1.27 allows type
parameters on a method only when the receiver is a concrete type ("interface
method must have no type parameters"). Generic methods are what let a chain
change type: Then[P], Par[B, R] and Map[P]. Runner stays an interface for
types that carry state.

Each cannot be a method: Step[I,O].Each returning Step[[]I,[]O] makes the
compiler instantiate Step[[][]I,[][]O] without end, which it rejects as an
instantiation cycle. It is a package-level function.

A step is now a value. Every method returns a new step, so middleware is
applied once at build time and a step is safe to share and to reuse.

Also:
  - Par, Fan and Each join every branch error with errors.Join and turn a
    panic into a *PanicError.
  - CircuitBreaker is an explicit value, so sharing is deliberate. v1 kept
    it in a closure, silently shared by every step the middleware wrapped.
  - Timeout starts no goroutine; v1 raced one and leaked it.
  - Log records the name, the duration and the error, never the payload.
  - No dependency outside the standard library. v1 needed mergo,
    google/uuid and x/sync.

CI runs a matrix over both modules, so v2 is tested as well.

98.2% coverage, clean under -race, go vet, modernize, go fix and
golangci-lint.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@veggiemonk
veggiemonk merged commit 084c0af into main Sep 21, 2026
2 checks passed
@veggiemonk
veggiemonk deleted the feat/v2 branch September 21, 2026 14:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant