durabletest

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package durabletest provides an in-memory local testing runner for durable handler functions. It enables fast, deterministic unit tests without requiring AWS credentials or network access.

The package runs a real durable executor against a thin in-memory durable.ExecutionClient implementation, so handler code executes exactly as it would in production — including checkpoint replay, operation ordering, and suspension semantics.

Quick Start

runner := durabletest.NewLocalRunner(myHandler)
result, err := runner.RunUntilComplete(myInput)
if err != nil {
    t.Fatal(err) // the runner failed
}
output, err := durabletest.ResultAs[MyOutput](result)
if err != nil {
    t.Fatal(err) // the handler failed, is pending, or the result did not decode
}

The runners do not take a test handle, so the same calls work in a plain main package, for example a program started with go run during local development.

Errors

The runner methods return a non-nil error only when the runner itself fails, and the TestResult is then nil:

The outcome of the handler is not an error. A handler that returns an error produces a nil error and a result with Status Failed and the recorded error in TestResult.Error. A run blocked on a callback or invoke produces a nil error and Status Pending. A run that reaches the invocation cap produces a nil error and TestResult.CapReached set to true. ResultAs returns an error for any result that did not succeed; for a failed handler its message includes the recorded error type and message.

The assertion helpers, such as AssertGoldenSignature, take a testing.TB, so tests, benchmarks, and fuzz tests can call them.

Execution Model

LocalRunner.Run performs a single invocation cycle. LocalRunner.RunUntilComplete loops automatically, advancing time between invocations until the execution reaches a terminal status or is blocked awaiting external resolution (callbacks, chained invokes).

The in-memory client validates each checkpoint against the service's limits and rejects an update the service rejects, with the service's error code and message: a step result or WaitForCondition state over 262144 bytes, an error object over 262144 bytes, an invoke input over 1048576 bytes, and a handler result checkpointed on the execution over 6291456 bytes. The SDK handles the rejection as it handles the service's: it fails the execution with a *durable.CheckpointError.

The client also rejects a checkpointed wait of zero seconds, as the service does. durable.Wait never sends one: it rejects a duration under one second at the call, with a plain error, and records no operation. So this check applies only to a malformed checkpoint sent to the client directly.

The client also reports an operation's completion in the invocation that observes it, not only between invocations. It keeps a virtual clock, which it uses for every timestamp it records. The clock is set when the execution starts, and wall-clock time does not move it. A wait records its scheduled end time and a step retry its next attempt time on this clock. The clock moves forward only on a request where the handler spent time: a poll, which the SDK sends while a goroutine is blocked, or a request that reports a step attempt or a child context finished. A request that only starts work, such as a step's START, moves nothing. On such a request the client moves the clock to the earliest due time among the waits and step retries that earlier requests started, and reports each one then due in that request's response: a wait as SUCCEEDED, a step retry or condition check as READY. A callback resolved with LocalRunner.SendCallbackSuccess or LocalRunner.SendCallbackFailure and an invoke settled by a registered function are reported in the response to the next checkpoint request. The handler then continues in the same invocation, as it does under the service. A wait the handler awaits with no other work under way still suspends the invocation.

The runner rejects a PENDING response that reports no pending operation, as the service does. It invokes the handler again, and the fourth such response in a row fails the execution with an InvalidParameterValueException.

External Resolution

For handlers that use callbacks or chained invokes, use RunUntilComplete to reach the PENDING state, then resolve the pending operation:

result, err := runner.RunUntilComplete(input) // returns PENDING
cbs := runner.OpenCallbacks()                 // enumerate pending callbacks
runner.SendCallbackSuccess(cbs[0].CallbackID, "payload")
result, err = runner.RunUntilComplete(input)  // now reaches SUCCEEDED

Chained invokes follow the same pattern:

result, err := runner.RunUntilComplete(input) // PENDING on invoke
runner.CompleteChainedInvoke("invoke-op", reply)
result, err = runner.RunUntilComplete(input)  // SUCCEEDED

Multi-Function Tests

Instead of stubbing an invoke's result, register the target function and let the invoke run it. LocalRunner.RegisterFunction binds a function identifier — the name or ARN the handler passes to durable.Invoke — to a Function built with DurableFunction or PlainFunction. A durable target runs as its own local execution with its own checkpoint log, so it suspends and resumes like the handler under test; a plain target is called once with the decoded input. The target runs when the invoke's START checkpoint arrives. Its result or error is recorded on the invoke and reported in the response to that checkpoint, so the caller reads it in the same invocation. Registered targets may invoke other registered identifiers, up to MaxInvokeDepth levels deep:

runner := durabletest.NewLocalRunner(orderHandler)
runner.RegisterFunction("pricing-function", durabletest.DurableFunction(pricingHandler))
runner.RegisterFunction("tax-function", durabletest.PlainFunction(taxHandler))
result, err := runner.RunUntilComplete(order) // runs both targets; SUCCEEDED

Invokes of identifiers that are not registered still block for LocalRunner.CompleteChainedInvoke, LocalRunner.FailChainedInvoke, or LocalRunner.TimeoutChainedInvoke, so the two styles mix within one test. This holds inside registered durable targets too: when a running target invokes an unregistered identifier, the same methods resolve that invoke, provided its name is open in only one execution. A durable target blocked on a callback leaves the caller's invoke STARTED; resolving that callback is not yet supported through the runner.

Inspecting Operations

TestResult provides accessors to look up operations by name, index, or ID. TestResult.OperationByNameAndIndex selects one occurrence of a name that a loop or a repeated child context checkpointed more than once. Each TestOperation carries typed detail getters for the operation's checkpoint state. When an assertion fails, TestResult.FormatTree renders the operations as an indented tree for the test log:

if result.Operation("charge") == nil {
    t.Fatalf("charge step missing:\n%s", result.FormatTree())
}

Reusing a Runner

A LocalRunner keeps its checkpoint log across calls so that successive invocations continue one execution. LocalRunner.Reset discards that log and every open callback and invoke while keeping the handler, its options, and the registered functions, so one runner can run several independent test cases.

Inspecting History

TestResult.Events is the execution's history event sequence and TestResult.Invocations has one record per completed invocation. Both runners populate them, so a test can assert on the event order or the number of invocations an execution needed in either environment:

result, err := runner.RunUntilComplete(input)
if err != nil {
    t.Fatal(err)
}
if got := len(result.Invocations); got != 3 {
    t.Fatalf("invocations = %d, want 3", got)
}
types := result.EventTypes() // e.g. ["ExecutionStarted", "StepStarted", ...]
Example

This example demonstrates the canonical usage of the local testing runner: create a runner, run a handler to completion, and inspect the typed result.

package main

import (
	"fmt"
	"time"

	"github.com/aws/aws-durable-execution-sdk-go/durable"
	"github.com/aws/aws-durable-execution-sdk-go/durable/durabletest"
)

func main() {
	// Define a durable handler that processes an order through multiple steps.
	handler := func(ctx durable.Context, event string) (string, error) {
		validated, err := durable.Step[string](ctx, "validate", func(_ durable.StepContext) (string, error) {
			return "valid:" + event, nil
		})
		if err != nil {
			return "", err
		}

		if err := durable.Wait(ctx, "cooldown", 5*time.Second); err != nil {
			return "", err
		}

		confirmed, err := durable.Step[string](ctx, "confirm", func(_ durable.StepContext) (string, error) {
			return "confirmed:" + validated, nil
		})
		if err != nil {
			return "", err
		}

		return confirmed, nil
	}

	// Create a local runner and run the handler to completion.
	// RunUntilComplete automatically advances the wait timer between
	// invocations. It returns an error only when the runner itself fails;
	// the handler's outcome is in the result.
	runner := durabletest.NewLocalRunner(handler)
	result, err := runner.RunUntilComplete("order-42")
	if err != nil {
		fmt.Println("Runner error:", err)
		return
	}

	fmt.Println("Status:", result.Status)

	output, err := durabletest.ResultAs[string](result)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println("Result:", output)

	// Inspect individual operations.
	validateOp := result.Operation("validate")
	fmt.Println("Validate status:", validateOp.Status)

}
Output:
Status: SUCCEEDED
Result: confirmed:valid:order-42
Validate status: SUCCEEDED

Index

Examples

Constants

View Source
const DefaultMaxInvocations = 100

DefaultMaxInvocations is the maximum number of re-invocations that LocalRunner.RunUntilComplete performs before returning.

View Source
const MaxInvokeDepth = 10

MaxInvokeDepth bounds how deeply registered functions may invoke one another. The handler passed to NewLocalRunner runs at depth 0. A registered function it invokes runs at depth 1, a registered function that one invokes runs at depth 2, and so on. An invoke that would start a registered function beyond MaxInvokeDepth does not run it: the invoke fails, and the caller receives a *durable.InvokeError whose ErrorType is "InvokeDepthExceeded". A registered function that invokes back into its caller's function identifier therefore stops after MaxInvokeDepth levels instead of recursing without limit.

Variables

This section is empty.

Functions

func AssertGoldenSignature

func AssertGoldenSignature(t testing.TB, result *TestResult, goldenPath string)

AssertGoldenSignature compares the event signature of result against a golden file at goldenPath. If the file does not exist or the environment variable UPDATE_GOLDEN is set to "1", the golden file is written (or overwritten) with the current signature.

On mismatch, the test fails with a diff showing expected vs actual.

Regenerating Golden Files

Set UPDATE_GOLDEN=1 to regenerate:

UPDATE_GOLDEN=1 go test ./durable/durabletest/ -run TestMyScenario

This follows the standard Go testdata golden-file convention.

func AssertGoldenSignatureUnordered

func AssertGoldenSignatureUnordered(t testing.TB, result *TestResult, goldenPath string)

AssertGoldenSignatureUnordered compares the event signature of result against a golden file at goldenPath using multiset (count-based) comparison rather than positional comparison. Use this when operations execute in parallel branches whose checkpoint ordering is non-deterministic.

The golden file records WHICH operations must be present and how many of each, but NOT their order.

Like AssertGoldenSignature, setting UPDATE_GOLDEN=1 regenerates the golden file. The golden file format is identical (a JSON array of OperationSignature); only the comparison semantics differ.

func AssertSignatureContains

func AssertSignatureContains(t testing.TB, result *TestResult, required []OperationSignature)

AssertSignatureContains verifies that the event signature of result contains all of the required operations (as a subset). Additional operations in the actual signature are tolerated. Use this when the set of operations depends on goroutine timing, for example when early completion leaves some branches unstarted.

Each required signature must appear at least once in the actual signature. Duplicate required entries require multiple actual matches.

func AssertSignatureExcludes

func AssertSignatureExcludes(t testing.TB, result *TestResult, excluded []OperationSignature)

AssertSignatureExcludes verifies that none of the excluded operations appear in the event signature. Use alongside AssertSignatureContains when specific operations must NOT be present.

func OperationResultAs

func OperationResultAs[O any](op *TestOperation) (O, error)

ResultAs deserializes the step result payload into the target type. It returns an error if the operation is not a step, has no result, or deserialization fails.

func ResultAs

func ResultAs[O any](r *TestResult) (O, error)

ResultAs deserializes the raw result of a Succeeded TestResult into the target type O. It returns an error when the execution did not succeed or deserialization fails. For a Failed execution the error message includes the recorded TestError.Type and TestError.Message, so a caller that checks the runner's error and then ResultAs's error learns why the handler failed.

ResultAs is a package-level generic function because Go methods cannot have type parameters.

Example (FailedHandler)

This example runs a handler that fails. The runner's error is nil, because the runner did its job; the result reports the failure, and ResultAs returns an error that names the handler's error.

package main

import (
	"errors"
	"fmt"

	"github.com/aws/aws-durable-execution-sdk-go/durable"
	"github.com/aws/aws-durable-execution-sdk-go/durable/durabletest"
)

func main() {
	handler := func(ctx durable.Context, _ string) (string, error) {
		return "", errors.New("card declined")
	}

	result, err := durabletest.NewLocalRunner(handler).RunUntilComplete("order-42")
	if err != nil {
		fmt.Println("Runner error:", err)
		return
	}
	fmt.Println("Status:", result.Status)

	if _, err := durabletest.ResultAs[string](result); err != nil {
		fmt.Println("Error:", err)
	}

}
Output:
Status: FAILED
Error: durabletest: cannot deserialize result from FAILED execution: Error: card declined

Types

type CloudRunner

type CloudRunner struct {
	// contains filtered or unexported fields
}

CloudRunner invokes a deployed durable Lambda function and polls the durable execution APIs until the execution reaches a terminal status. It then maps the result and operation log into the same TestResult and TestOperation types that LocalRunner returns, enabling the same assertions to be used regardless of execution environment.

CloudRunner requires a caller-supplied DurableExecutionAPI implementation (typically a real *lambda.Client) and a function identifier (name or ARN).

Example

ctx := context.Background()
cfg, _ := config.LoadDefaultConfig(ctx)
client := lambda.NewFromConfig(cfg)
runner := durabletest.NewCloudRunner(client, "my-function:$LATEST")
result, err := runner.Run(ctx, `{"orderId": "123"}`)

func NewCloudRunner

func NewCloudRunner(api DurableExecutionAPI, functionName string, opts ...CloudRunnerOption) *CloudRunner

NewCloudRunner creates a runner targeting the given deployed durable function. The api parameter accepts any implementation of DurableExecutionAPI; in production this is typically a *lambda.Client from aws-sdk-go-v2.

functionName must be a qualified function identifier (name, ARN, or partial ARN with version/alias qualifier).

func (*CloudRunner) Run

func (r *CloudRunner) Run(ctx context.Context, event any) (*TestResult, error)

Run invokes the function with event (JSON-encoded), polls until the execution reaches a terminal status, and returns the TestResult. Run passes ctx to the Lambda Invoke call and to every poll, so a deadline or cancellation on ctx ends the run.

The returned error is non-nil only when the runner itself fails: the event does not marshal to JSON, the Invoke call fails, the invoke response has no DurableExecutionArn, polling fails or exceeds the WithTimeout limit, or ctx ends. The result is then nil. An execution that fails produces a nil error and a Failed result with the recorded error in TestResult.Error.

func (*CloudRunner) RunWithArn

func (r *CloudRunner) RunWithArn(ctx context.Context, executionArn string) (*TestResult, error)

RunWithArn polls an already-started execution by ARN until it reaches a terminal status. Use this when the execution was started externally (e.g. async invoke). The error contract is the one CloudRunner.Run states, minus the Invoke call: the error is non-nil, and the result nil, only when polling fails, exceeds the WithTimeout limit, or ctx ends.

func (*CloudRunner) SendCallbackFailure

func (r *CloudRunner) SendCallbackFailure(callbackID, errorType, errorMessage string) error

SendCallbackFailure fails a pending callback with a typed error, mirroring LocalRunner.SendCallbackFailure.

func (*CloudRunner) SendCallbackHeartbeat

func (r *CloudRunner) SendCallbackHeartbeat(callbackID string) error

SendCallbackHeartbeat extends the heartbeat timeout of a pending callback, mirroring LocalRunner.SendCallbackHeartbeat.

func (*CloudRunner) SendCallbackSuccess

func (r *CloudRunner) SendCallbackSuccess(callbackID string, payload any) error

SendCallbackSuccess resolves a pending callback with a success payload, mirroring LocalRunner.SendCallbackSuccess.

type CloudRunnerOption

type CloudRunnerOption func(*cloudRunnerConfig)

CloudRunnerOption configures a CloudRunner.

func WithPollInterval

func WithPollInterval(d time.Duration) CloudRunnerOption

WithPollInterval sets the interval between GetDurableExecution polls. Defaults to 2 seconds.

func WithTimeout

func WithTimeout(d time.Duration) CloudRunnerOption

WithTimeout sets the maximum time CloudRunner will spend polling before returning an error. Defaults to 5 minutes.

type DurableExecutionAPI

type DurableExecutionAPI interface {
	// GetDurableExecution retrieves execution metadata including status
	// and result.
	GetDurableExecution(ctx context.Context, params *lambda.GetDurableExecutionInput, optFns ...func(*lambda.Options)) (*lambda.GetDurableExecutionOutput, error)

	// GetDurableExecutionHistory retrieves the execution's event
	// history.
	GetDurableExecutionHistory(ctx context.Context, params *lambda.GetDurableExecutionHistoryInput, optFns ...func(*lambda.Options)) (*lambda.GetDurableExecutionHistoryOutput, error)

	// Invoke starts or resumes a durable function invocation.
	Invoke(ctx context.Context, params *lambda.InvokeInput, optFns ...func(*lambda.Options)) (*lambda.InvokeOutput, error)

	// SendDurableExecutionCallbackSuccess completes a callback with
	// success.
	SendDurableExecutionCallbackSuccess(ctx context.Context, params *lambda.SendDurableExecutionCallbackSuccessInput, optFns ...func(*lambda.Options)) (*lambda.SendDurableExecutionCallbackSuccessOutput, error)

	// SendDurableExecutionCallbackFailure completes a callback with
	// failure.
	SendDurableExecutionCallbackFailure(ctx context.Context, params *lambda.SendDurableExecutionCallbackFailureInput, optFns ...func(*lambda.Options)) (*lambda.SendDurableExecutionCallbackFailureOutput, error)

	// SendDurableExecutionCallbackHeartbeat extends a callback timeout.
	SendDurableExecutionCallbackHeartbeat(ctx context.Context, params *lambda.SendDurableExecutionCallbackHeartbeatInput, optFns ...func(*lambda.Options)) (*lambda.SendDurableExecutionCallbackHeartbeatOutput, error)
}

DurableExecutionAPI is the subset of the Lambda service client that CloudRunner requires. It covers execution lifecycle queries and callback operations. Callers supply a real *lambda.Client or a test fake implementing these methods.

type ExecutionStatus

type ExecutionStatus string

ExecutionStatus represents the outcome of a durable execution invocation.

const (
	Succeeded ExecutionStatus = "SUCCEEDED"
	Failed    ExecutionStatus = "FAILED"
	Pending   ExecutionStatus = "PENDING"
)

Execution status values.

type Function

type Function struct {
	// contains filtered or unexported fields
}

Function is a handler registered with LocalRunner.RegisterFunction as the target of a chained invoke. Construct one with DurableFunction or PlainFunction; the zero value is not usable.

func DurableFunction

func DurableFunction[I, O any](handler durable.Handler[I, O], opts ...durable.HandlerOption) Function

DurableFunction makes a durable handler registrable as an invoke target. When the workflow under test invokes the identifier the Function is registered under, the runner starts a separate local execution for handler, with its own in-memory client and its own checkpoint log, and feeds the invoke's serialized input to it as the execution input.

The opts configure the target handler the same way the opts of NewLocalRunner configure the handler under test.

func PlainFunction

func PlainFunction[I, O any](handler func(context.Context, I) (O, error)) Function

PlainFunction makes a non-durable handler registrable as an invoke target. The handler has the shape of an ordinary typed Lambda handler. When the workflow under test invokes the identifier the Function is registered under, the runner decodes the invoke's input as JSON into I, calls handler once, and encodes the returned O as JSON for the invoke's result. A returned error fails the invoke; its ErrorType is the error's Go type name, or "Error" for an unnamed type such as one produced by errors.New or fmt.Errorf.

type LocalRunner

type LocalRunner[I, O any] struct {
	// contains filtered or unexported fields
}

LocalRunner executes a durable handler function locally using an in-memory execution client. Each [Run] call performs a single invocation cycle: the handler sees any previously checkpointed state plus the new input, checkpoints new operations, and returns a TestResult.

Use [RunUntilComplete] to loop automatically until the execution reaches a terminal status (SUCCEEDED or FAILED) or until it is blocked awaiting external resolution (callbacks, chained invokes).

LocalRunner does not depend on the testing package, so a plain main program can drive a handler with it as well as a test can.

LocalRunner is safe for sequential use from a single goroutine. It is NOT safe for concurrent use from multiple goroutines.

func NewLocalRunner

func NewLocalRunner[I, O any](handler durable.Handler[I, O], opts ...durable.HandlerOption) *LocalRunner[I, O]

NewLocalRunner creates a runner for the given durable handler function. The handler is wired to an in-memory execution client; no AWS credentials or network access is required.

Additional durable.HandlerOption values (such as durable.WithSerdes) can be passed to configure the handler exactly as it would be in production, minus the execution client.

func (*LocalRunner[I, O]) CompleteChainedInvoke

func (r *LocalRunner[I, O]) CompleteChainedInvoke(name string, payload any) error

CompleteChainedInvoke resolves a pending chained-invoke operation with a success result. The name must match the operation name passed to durable.Invoke. The payload is serialized to JSON and stored in ChainedInvokeDetails.Result.

The invoke may belong to the handler under test or to a registered durable target the runner is running (see [RegisterFunction]), at any depth. Exactly one open invoke may carry the name; if the handler and a running target both have an open invoke of that name, the call returns an error and settles nothing.

func (*LocalRunner[I, O]) CompletePendingTimers

func (r *LocalRunner[I, O]) CompletePendingTimers() bool

CompletePendingTimers completes every operation that is blocked on a timer at once, regardless of its scheduled time. Exactly two kinds of operations are affected:

  • A step awaiting a retry timer (PENDING) becomes ready for re-execution (READY). This includes the delays between durable.WaitForCondition checks.
  • A wait whose duration has not yet elapsed (STARTED) completes (SUCCEEDED).

No other operations are touched: callbacks and chained invokes remain blocked until resolved explicitly.

The in-memory client keeps a virtual clock, set when the execution starts and not moved by wall-clock time. A wait records its scheduled end time and a step retry its next attempt time on that clock. CompletePendingTimers fires every pending timer regardless of its scheduled time, and moves the clock forward to the latest of those times. A timed operation is also reported without this call: on a poll, or on a request that reports a step attempt or a child context finished, the client moves its clock to the earliest due time among the timers earlier requests started and reports each operation then due in the response, so the handler continues in the same invocation.

Returns true if any operation was completed.

func (*LocalRunner[I, O]) FailChainedInvoke

func (r *LocalRunner[I, O]) FailChainedInvoke(name, errorType, errorMessage string) error

FailChainedInvoke fails a pending chained-invoke operation with a typed error. The resulting *durable.InvokeError carries these values when the handler re-invokes and encounters the FAILED status.

The invoke is located the same way as in [CompleteChainedInvoke]: in the handler under test or in any registered durable target the runner is running, and the name must be open in exactly one of them.

func (*LocalRunner[I, O]) OmitTokenOnCheckpoint

func (r *LocalRunner[I, O]) OmitTokenOnCheckpoint(n int)

OmitTokenOnCheckpoint makes the n-th checkpoint call from now (1-based) return a response without a checkpoint token. It simulates the service signaling that it will accept no further checkpoints from the current invocation.

The handler observes this the way it would in production: the SDK stops checkpointing, and the invocation ends with Pending. Operations whose checkpoint was in the tokenless response are recorded; operations that had not yet checkpointed replay on the next invocation. LocalRunner.RunUntilComplete returns that PENDING result, since no timer or external action is needed to continue; a further Run or RunUntilComplete resumes from the recorded state. Use it to test that a handler tolerates an invocation ending mid-flight:

runner.OmitTokenOnCheckpoint(1)
result, err := runner.RunUntilComplete(input) // PENDING after the first checkpoint
result, err = runner.RunUntilComplete(input)  // resumes from the recorded state

Count calls, not operations: a step checkpoints twice, once when it starts and once when it settles, so OmitTokenOnCheckpoint(2) withholds the token on the first step's result. A status poll the SDK sends while a goroutine awaits an unfinished operation is a checkpoint call with no updates, so it counts toward n too. Calls are counted from the moment of scheduling.

A call that carries the execution's terminal update, the checkpoint that records a result too large for the response, is the exception: a response without a token to it means the execution finished, so the run reports SUCCEEDED.

A later call replaces a schedule that has not fired yet. n must be at least 1; OmitTokenOnCheckpoint panics otherwise.

func (*LocalRunner[I, O]) OpenCallbacks

func (r *LocalRunner[I, O]) OpenCallbacks() []OpenCallback

OpenCallbacks returns the callback IDs of all CALLBACK operations currently in STARTED status (pending external resolution). The returned IDs can be passed to [SendCallbackSuccess], [SendCallbackFailure], or [SendCallbackHeartbeat].

func (*LocalRunner[I, O]) RegisterFunction

func (r *LocalRunner[I, O]) RegisterFunction(functionID string, fn Function)

RegisterFunction registers fn as the target of chained invokes of functionID, the function name or ARN the handler under test passes to durable.Invoke. Build fn with DurableFunction or PlainFunction. Registering the same identifier again replaces the earlier target.

When the handler under test starts an invoke of a registered identifier, the runner executes the registered target as the invoke's START checkpoint arrives. A durable target runs as its own local execution with its own checkpoint log: it suspends and resumes on its own timers, and when it settles its result or error is recorded on the caller's invoke operation. A non-durable target is called once. The response to the START checkpoint reports the outcome, so the caller observes it in the same invocation, as it would observe [CompleteChainedInvoke] or [FailChainedInvoke]: a success returns the decoded result and a failure returns a *durable.InvokeError.

Registered targets may themselves invoke registered identifiers, up to MaxInvokeDepth levels deep. A durable target that blocks on external action, such as a callback, leaves the caller's invoke STARTED; when an invocation of the caller ends with that invoke still open, [Run] and [RunUntilComplete] drive the target again before returning.

Invokes of identifiers that are not registered are unaffected: they stay STARTED until resolved with [CompleteChainedInvoke] or [FailChainedInvoke].

Example

This example registers the functions a workflow invokes so the chained invokes run for real instead of being stubbed. The pricing function is a durable handler with its own checkpoint log; the tax function is a plain handler called once.

package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-durable-execution-sdk-go/durable"
	"github.com/aws/aws-durable-execution-sdk-go/durable/durabletest"
)

func main() {
	type order struct {
		Quantity int `json:"quantity"`
	}

	pricing := func(ctx durable.Context, o order) (int, error) {
		return durable.Step(ctx, "lookup", func(durable.StepContext) (int, error) {
			return o.Quantity * 10, nil
		})
	}
	tax := func(_ context.Context, subtotal int) (int, error) {
		return subtotal / 10, nil
	}

	handler := func(ctx durable.Context, o order) (int, error) {
		subtotal, err := durable.Invoke[int](ctx, "price", "pricing-function", o)
		if err != nil {
			return 0, err
		}
		taxDue, err := durable.Invoke[int](ctx, "tax", "tax-function", subtotal)
		if err != nil {
			return 0, err
		}
		return subtotal + taxDue, nil
	}

	runner := durabletest.NewLocalRunner(handler)
	runner.RegisterFunction("pricing-function", durabletest.DurableFunction(pricing))
	runner.RegisterFunction("tax-function", durabletest.PlainFunction(tax))

	result, err := runner.RunUntilComplete(order{Quantity: 3})
	if err != nil {
		fmt.Println("Runner error:", err)
		return
	}
	fmt.Println("Status:", result.Status)

	total, err := durabletest.ResultAs[int](result)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println("Total:", total)
	fmt.Println("Price invoke:", result.Operation("price").Status)

}
Output:
Status: SUCCEEDED
Total: 33
Price invoke: SUCCEEDED

func (*LocalRunner[I, O]) Reset

func (r *LocalRunner[I, O]) Reset()

Reset returns the runner to the state it had when NewLocalRunner returned it, so the next [Run] or [RunUntilComplete] starts a new execution from scratch. It discards the checkpoint log, the recorded history events, every open callback and chained invoke, any registered durable target still running, and any [OmitTokenOnCheckpoint] schedule that has not fired. Invocation request IDs count from 1 again.

The handler and the durable.HandlerOption values passed to NewLocalRunner are kept, as is the invocation cap. Functions registered with [RegisterFunction] are kept as well: they describe the environment the handler runs in, not the state of one execution, so a test can register targets once and reset between cases.

Reset is not safe to call while [Run] or [RunUntilComplete] is in progress. Call it only between invocations, from the goroutine that drives the runner.

Results returned by earlier calls are unaffected: a TestResult is a snapshot and does not reference the runner.

func (*LocalRunner[I, O]) Run

func (r *LocalRunner[I, O]) Run(event I) (*TestResult, error)

Run performs a single durable invocation against the in-memory client. It constructs the invocation payload from the current checkpoint state, invokes the handler, and returns the result.

On a fresh runner, Run starts a new execution. On subsequent calls, it re-invokes with the accumulated checkpoint state, simulating the Lambda re-invocation loop.

A registered function the handler invokes runs when the invoke starts (see [RegisterFunction]). After the handler returns, Run drives again any registered durable target that is still open. The returned operations reflect the state after those targets ran. A registered durable target is driven for up to the invocation cap (DefaultMaxInvocations) within one Run; if it exhausts the cap without settling, TestResult.CapReached is true.

The returned error is non-nil only when the runner itself fails: the event does not marshal to JSON, the invocation returns an error that indicates an SDK or runner bug, or the response does not parse. The result is then nil. The outcome of the handler is never an error: a handler that returns an error produces a Failed result with the recorded error in TestResult.Error, and an invocation that suspends produces a Pending result.

func (*LocalRunner[I, O]) RunUntilComplete

func (r *LocalRunner[I, O]) RunUntilComplete(event I, opts ...RunnerOption) (*TestResult, error)

RunUntilComplete performs repeated invocations until the execution reaches a terminal status (SUCCEEDED or FAILED), is blocked awaiting external resolution, or the invocation cap is reached.

Between invocations, RunUntilComplete automatically advances time-eligible operations (STEP in PENDING → READY for retry, WAIT in STARTED → SUCCEEDED) and executes registered functions the handler invoked (see [RegisterFunction]). If no operations can be auto-advanced, no registered target settled, and the execution is still PENDING, the method returns the PENDING result without spinning — this indicates that external action (callback submission, chained-invoke completion) is required before progress can continue.

A PENDING response that reports no pending operation is one the service rejects. A pending operation is a wait, callback, or chained invoke in STARTED status, or a step in STARTED, PENDING, or READY status. After such a response RunUntilComplete invokes the handler again, as the service does, and the fourth such response in a row fails the execution: TestResult.Status is Failed and TestResult.Error has Type "InvalidParameterValueException" and Message "Cannot return PENDING status with no pending operations.". A PENDING response with a pending operation resets the count. A response that follows a checkpoint whose token was withheld (see LocalRunner.OmitTokenOnCheckpoint) is not counted.

The invocation cap defaults to DefaultMaxInvocations (100) and can be changed with WithMaxInvocations. The same cap applies to each registered durable target. If the cap is exhausted, the final result (typically PENDING) is returned with TestResult.CapReached set to true.

The error contract is the one LocalRunner.Run states: the error is non-nil, and the result nil, only when the runner itself fails. A failed handler, a run blocked on a callback or invoke, and a run that reaches the invocation cap all return a nil error and a result whose TestResult.Status and TestResult.CapReached describe the outcome.

func (*LocalRunner[I, O]) SendCallbackFailure

func (r *LocalRunner[I, O]) SendCallbackFailure(callbackID, errorType, errorMessage string) error

SendCallbackFailure fails a pending callback operation with a typed error, matching the wire behavior of the SendDurableExecutionCallbackFailure API.

The errorType and errorMessage map to ErrorObject.ErrorType and ErrorObject.ErrorMessage on the wire. The resulting *durable.CallbackError carries these values so callers in test code can inspect them with errors.As.

func (*LocalRunner[I, O]) SendCallbackHeartbeat

func (r *LocalRunner[I, O]) SendCallbackHeartbeat(callbackID string) error

SendCallbackHeartbeat extends the heartbeat timeout of a pending callback operation, matching the wire behavior of the SendDurableExecutionCallbackHeartbeat API.

In the local testing runner, this is a no-op that validates the callback exists and is in STARTED status. Real heartbeat timeout mechanics are not simulated locally.

func (*LocalRunner[I, O]) SendCallbackSuccess

func (r *LocalRunner[I, O]) SendCallbackSuccess(callbackID string, payload any) error

SendCallbackSuccess completes a pending callback operation with a success result. The callbackID is the hashed operation ID visible via TestOperation.CallbackDetails or [OpenCallbacks].

The payload is serialized to JSON and stored in CallbackDetails.Result, matching the wire behavior of the SendDurableExecutionCallbackSuccess API.

func (*LocalRunner[I, O]) TimeoutCallback

func (r *LocalRunner[I, O]) TimeoutCallback(callbackID string) error

TimeoutCallback transitions a pending callback operation to TIMED_OUT, simulating the backend behavior when a callback's configured timeout elapses without external resolution.

After calling TimeoutCallback, invoke [Run] or [RunUntilComplete] to allow the handler to observe the timeout and continue execution.

func (*LocalRunner[I, O]) TimeoutChainedInvoke

func (r *LocalRunner[I, O]) TimeoutChainedInvoke(name string) error

TimeoutChainedInvoke transitions a pending chained-invoke operation to TIMED_OUT status, simulating the invoked function's execution running past its timeout before it produced a result. The resulting *durable.InvokeError unwraps to durable.ErrInvokeTimedOut when the handler re-invokes and encounters the TIMED_OUT status.

The invoke is located the same way as in [CompleteChainedInvoke]: in the handler under test or in any registered durable target the runner is running, and the name must be open in exactly one of them.

After calling TimeoutChainedInvoke, invoke [Run] or [RunUntilComplete] to allow the handler to observe the timeout and continue execution.

type OpenCallback

type OpenCallback struct {
	// CallbackID is the identifier to pass to [LocalRunner.SendCallbackSuccess]
	// or [LocalRunner.SendCallbackFailure].
	CallbackID string

	// Name is the caller-supplied operation name.
	Name string
}

OpenCallback identifies a callback operation pending external resolution.

type OperationSignature

type OperationSignature struct {
	// Type is the operation type (e.g. "STEP", "WAIT", "CALLBACK").
	Type string `json:"type"`

	// SubType further qualifies the type (e.g. "Step",
	// "WaitForCondition", "RunInChildContext").
	SubType string `json:"subType,omitempty"`

	// Name is the user-assigned operation name, empty for unnamed ops.
	Name string `json:"name,omitempty"`

	// Status is the operation's terminal or last-observed status.
	Status string `json:"status"`
}

OperationSignature is the deterministic, comparable subset of a single checkpointed operation's identity. It captures the operation's type, subtype, name, and status — the shape of the operation log — while normalizing away timestamps, tokens, hashed IDs, and other run-specific values that would make golden files brittle.

func EventSignature

func EventSignature(result *TestResult) []OperationSignature

EventSignature derives a stable, deterministic signature from a TestResult's operation log. The signature captures the type/subtype/name/status sequence of operations while normalizing away timestamps, tokens, hashed IDs, and other run-specific values.

This is useful for golden-file assertions: the signature captures WHAT operations ran and in what order, without being brittle to irrelevant changes between runs.

type RunnerOption

type RunnerOption func(*runnerConfig)

RunnerOption configures a LocalRunner.

func WithMaxInvocations

func WithMaxInvocations(n int) RunnerOption

WithMaxInvocations overrides the invocation cap for LocalRunner.RunUntilComplete. The default is DefaultMaxInvocations.

type TestCallbackDetails

type TestCallbackDetails struct {
	// CallbackID is the identifier for external callback submission.
	CallbackID string

	// Result is the serialized callback result (present on SUCCEEDED).
	Result string

	// ErrorType is the recorded error type (present on FAILED).
	ErrorType string

	// ErrorMessage is the recorded error message (present on FAILED).
	ErrorMessage string

	// ErrorData is the recorded machine-readable error data, set on failure.
	ErrorData string

	// StackTrace is the recorded stack trace of the failure, innermost
	// frame first, set on failure.
	StackTrace []string
}

TestCallbackDetails carries callback-specific checkpoint state.

type TestContextDetails

type TestContextDetails struct {
	// Result is the serialized context result (present on SUCCEEDED).
	Result string

	// ReplayChildren indicates the context uses replay-children mode for
	// large payloads.
	ReplayChildren bool

	// ErrorType is the recorded error type (present on FAILED).
	ErrorType string

	// ErrorMessage is the recorded error message (present on FAILED).
	ErrorMessage string

	// ErrorData is the recorded machine-readable error data, set on failure.
	ErrorData string

	// StackTrace is the recorded stack trace of the failure, innermost
	// frame first, set on failure.
	StackTrace []string
}

TestContextDetails carries child-context-specific checkpoint state.

type TestError

type TestError struct {
	// Type is the error's type name (e.g. "StepError", "InvokeError").
	Type string

	// Message is the human-readable error message.
	Message string

	// ErrorData is the recorded machine-readable error data, if any.
	ErrorData string

	// StackTrace is the recorded stack trace, innermost frame first, if any.
	StackTrace []string
}

TestError carries the error information from a FAILED invocation.

type TestInvocation

type TestInvocation struct {
	// RequestID identifies the invocation. Under [CloudRunner] it is the
	// Lambda request ID. Under [LocalRunner] it is assigned by the runner
	// and counts invocations of the execution from 1; it is not a Lambda
	// request ID.
	RequestID string

	// StartTime is when the invocation started.
	StartTime time.Time

	// EndTime is when the invocation ended.
	EndTime time.Time

	// Error holds the error the invocation ended with, or nil if it ended
	// without one. Under [LocalRunner] it is set when the invocation's
	// response ended the execution as FAILED, and matches
	// [TestResult.Error] in that case.
	Error *TestError
}

TestInvocation records one completed invocation of the handler.

type TestInvokeDetails

type TestInvokeDetails struct {
	// Result is the serialized invoke result (present on SUCCEEDED).
	Result string

	// ErrorType is the recorded error type (present on FAILED).
	ErrorType string

	// ErrorMessage is the recorded error message (present on FAILED).
	ErrorMessage string

	// ErrorData is additional error data (present on some failures).
	ErrorData string

	// StackTrace is the recorded stack trace of the failure, innermost
	// frame first, set on failure.
	StackTrace []string
}

TestInvokeDetails carries chained-invoke-specific checkpoint state.

type TestOperation

type TestOperation struct {
	// ID is the wire operation ID (hashed).
	ID string

	// Name is the caller-supplied operation name, or empty for unnamed
	// operations.
	Name string

	// Status is the operation's current status.
	Status string

	// Type is the operation type (e.g. "STEP", "WAIT", "CALLBACK").
	Type string

	// SubType further qualifies the operation type (e.g. "Step",
	// "WaitForCondition", "RunInChildContext").
	SubType string

	// ParentID is the parent operation's wire ID, or empty for top-level
	// operations.
	ParentID string

	// StartTime is when the operation first reached STARTED status, or the
	// zero time when the runner has no record of it. [CloudRunner] fills
	// it from the execution history; [LocalRunner] records the wall-clock
	// time of the checkpoint that started the operation.
	StartTime time.Time

	// EndTime is when the operation reached a terminal status, or the
	// zero time when it has not or the runner has no record of it. For
	// [LocalRunner] it is the wall-clock time of the checkpoint or runner
	// call that settled the operation.
	EndTime time.Time

	// StepDetails holds step-specific details, if the operation is a step.
	StepDetails *TestStepDetails

	// CallbackDetails holds callback-specific details, if the operation
	// is a callback.
	CallbackDetails *TestCallbackDetails

	// InvokeDetails holds chained-invoke-specific details, if the
	// operation is a chained invoke.
	InvokeDetails *TestInvokeDetails

	// ContextDetails holds child-context-specific details, if the
	// operation is a context.
	ContextDetails *TestContextDetails

	// WaitDetails holds wait-specific details, if the operation is a
	// wait.
	WaitDetails *TestWaitDetails
}

TestOperation represents a single checkpointed durable operation.

func (*TestOperation) IsTerminal

func (o *TestOperation) IsTerminal() bool

IsTerminal reports whether the operation has reached a terminal status (SUCCEEDED, FAILED, CANCELLED, TIMED_OUT, STOPPED).

type TestResult

type TestResult struct {
	// Status is the invocation outcome.
	Status ExecutionStatus

	// RawResult is the JSON-encoded handler result. Present only when
	// Status is [Succeeded]. Use [ResultAs] to deserialize.
	RawResult string

	// Error holds the error details when Status is [Failed].
	Error *TestError

	// Operations is the ordered list of operations checkpointed during
	// this invocation, excluding the execution operation itself.
	Operations []TestOperation

	// CapReached is true if [LocalRunner.RunUntilComplete] exhausted its
	// invocation cap without reaching a terminal status.
	CapReached bool

	// Events is the execution's history event sequence, oldest first.
	// [CloudRunner] returns the events the service recorded. [LocalRunner]
	// returns the events it recorded while running the handler: one per
	// checkpointed operation update, one per transition it applied
	// between invocations (timers, callbacks, chained invokes), one
	// InvocationCompleted per invocation, and the execution's start and
	// terminal events. Event IDs count from 1 in each runner.
	//
	// Fields the local runner has no source for are left unset rather
	// than filled in: ExecutionStartedDetails.ExecutionTimeout,
	// ChainedInvokeStartedDetails.DurableExecutionArn and
	// ExecutedVersion, and the Truncated flag on payloads. Local event
	// timestamps are wall-clock times of recording.
	Events []types.Event

	// Invocations records each completed invocation of the handler, oldest
	// first. It is derived from the InvocationCompleted events in Events,
	// so it is populated by [LocalRunner] and [CloudRunner] alike.
	Invocations []TestInvocation
}

TestResult holds the outcome of a single LocalRunner.Run invocation. It captures the execution status, raw result payload, error details, and the operations that were checkpointed during the invocation.

func (*TestResult) EventTypes

func (r *TestResult) EventTypes() []string

EventTypes returns the type of each event in TestResult.Events, in order, as strings (e.g. "ExecutionStarted", "StepStarted", "InvocationCompleted").

func (*TestResult) FormatTree

func (r *TestResult) FormatTree(columns ...TreeColumn) string

FormatTree renders the operations of the result as an indented tree and returns the text. Each operation is one row; a child operation is indented under its parent, and children keep the order they have in TestResult.Operations. The first line is a header naming the columns.

columns selects which columns are rendered, in the given order. With no columns, the DefaultTreeColumns set is used. Empty values render as "-".

An operation whose ParentID names no operation in the result is rendered at the top level rather than dropped. The output depends only on the result's operations, so it is deterministic for a given result and can be compared in tests.

Pass the text to the test logger to see the tree when an assertion fails:

t.Log(result.FormatTree())

func (*TestResult) Operation

func (r *TestResult) Operation(name string) *TestOperation

Operation returns the first operation with the given name, or nil if not found.

func (*TestResult) OperationByID

func (r *TestResult) OperationByID(id string) *TestOperation

OperationByID returns the operation with the given wire ID (hashed), or nil if not found.

func (*TestResult) OperationByIndex

func (r *TestResult) OperationByIndex(index int) *TestOperation

OperationByIndex returns the operation at the given zero-based index, or nil if the index is out of bounds.

func (*TestResult) OperationByNameAndIndex

func (r *TestResult) OperationByNameAndIndex(name string, index int) *TestOperation

OperationByNameAndIndex returns the index-th operation named name, counting from zero, or nil if fewer than index+1 operations carry the name or index is negative. Occurrences are counted in the order of TestResult.Operations, so OperationByNameAndIndex(name, 0) is the same operation TestResult.Operation returns. Use it when a workflow runs the same named operation more than once, such as a step inside a loop or a repeated child context.

func (*TestResult) OperationsByType

func (r *TestResult) OperationsByType(opType string) []TestOperation

OperationsByType returns all operations of the given type string (e.g. "STEP", "WAIT", "CALLBACK", "CHAINED_INVOKE", "CONTEXT").

func (*TestResult) WriteTree

func (r *TestResult) WriteTree(w io.Writer, columns ...TreeColumn) error

WriteTree renders the same text as TestResult.FormatTree to w. It returns the first error w reports.

type TestStepDetails

type TestStepDetails struct {
	// Attempt is the number of attempts recorded.
	Attempt int32

	// Result is the serialized step result (present on SUCCEEDED).
	Result string

	// ErrorType is the recorded error type (present on FAILED/PENDING).
	ErrorType string

	// ErrorMessage is the recorded error message.
	ErrorMessage string

	// NextAttemptTimestamp is when the next retry attempt is scheduled, or
	// the zero time when no retry is pending.
	NextAttemptTimestamp time.Time

	// ErrorData is the recorded machine-readable error data, set on failure.
	ErrorData string

	// StackTrace is the recorded stack trace of the failure, innermost
	// frame first, set on failure.
	StackTrace []string
}

TestStepDetails carries step-specific checkpoint state.

type TestWaitDetails

type TestWaitDetails struct {
	// WaitSeconds is the wait duration in seconds that the WaitStarted
	// history event records, or 0 when the history has no such event.
	WaitSeconds int

	// ScheduledEndTimestamp is when the wait is scheduled to complete, or
	// the zero time when the operation record carries no scheduled end.
	ScheduledEndTimestamp time.Time
}

TestWaitDetails carries wait-specific checkpoint state.

type TreeColumn

type TreeColumn int

TreeColumn selects one column of the operation tree rendered by TestResult.FormatTree and TestResult.WriteTree.

const (
	// ColumnName is the operation name, indented by nesting depth.
	ColumnName TreeColumn = iota
	// ColumnType is the operation type (e.g. "STEP", "CONTEXT").
	ColumnType
	// ColumnSubType is the operation subtype (e.g. "Step",
	// "RunInChildContext").
	ColumnSubType
	// ColumnStatus is the operation status (e.g. "SUCCEEDED").
	ColumnStatus
	// ColumnStartTime is [TestOperation.StartTime] in UTC.
	ColumnStartTime
	// ColumnEndTime is [TestOperation.EndTime] in UTC.
	ColumnEndTime
	// ColumnDuration is EndTime minus StartTime.
	ColumnDuration
	// ColumnID is the operation's wire ID.
	ColumnID
	// ColumnParentID is the parent operation's wire ID.
	ColumnParentID
)

Columns available to TestResult.FormatTree and TestResult.WriteTree.

func DefaultTreeColumns

func DefaultTreeColumns() []TreeColumn

DefaultTreeColumns returns the column set TestResult.FormatTree and TestResult.WriteTree render when called with no columns: name, type, subtype, status, start time, end time, and duration, in that order. Each call returns a new slice, so a caller can append to or reorder the result without changing the default.

func (TreeColumn) String

func (c TreeColumn) String() string

String returns the column's header label.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL