Java / Advanced / Lesson 21
CompletableFuture composition and failure
Compose Java CompletableFuture stages and handle asynchronous failures.
On this page
Lesson goals
- Transform a completed stage.
- Test failure and execution policies.
- Distinguish stage transformation, flattening, and combination from execution policy.
- Design observable and testable recovery, cancellation, and executor ownership.
Define stage ownership
A CompletableFuture represents an eventual result and lets stages describe dependent work. Define which stage owns failure handling and when the caller waits for completion. A stage may already be complete when attached; do not assume that composing a stage necessarily starts a new thread. Keep side effects and shared-state ownership explicit across the asynchronous boundary.
Transform a result
thenApply transforms a successful result into another value. The example begins with a completed future, doubles its value, and joins the resulting stage. This fixed setup demonstrates composition without relying on scheduling or an external service. A function that itself returns a future usually calls for thenCompose when the intended result is a single flattened stage rather than a nested future.
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
var result = CompletableFuture.completedFuture(21)
.thenApply(value -> value * 2);
System.out.println(result.join());
}
}
42
The completed value is transformed to 42.
Handle failure deliberately
A failed stage propagates failure unless a later stage handles it. handle receives either the value or an exception and can produce a deliberate fallback; the example uses a synthetic failed future and checks the exception branch. A fallback must be justified by the domain. If failure should remain visible, preserve or rethrow it rather than silently returning plausible success.
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
var failed = CompletableFuture.<Integer>failedFuture(
new IllegalStateException("synthetic"));
var recovered = failed.handle((value, error) -> error == null ? value : 0);
System.out.println(recovered.join());
}
}
0
The synthetic failure selects the documented fallback.
Choose execution policy
Execution policy matters for blocking or expensive stages. The asynchronous variants can use an executor; make its ownership and shutdown responsibilities explicit when supplying one. Avoid blocking a worker while waiting for work that needs the same constrained executor. Cancellation and timeout behavior also need an application contract: completing a future exceptionally does not automatically undo external side effects.
Test stage outcomes
Test successful transformation, an exceptional stage, and the selected recovery policy with controlled futures. Assert the final result or failure rather than exact scheduling order. For code that owns an executor, test shutdown and ensure all tasks finish or are handled. Include a case where a fallback is not allowed so error handling cannot accidentally turn every failure into success.
Draw the dependency graph before scheduling
A CompletableFuture represents an eventual outcome, and dependent stages describe computations triggered by other stages. Draw which values each stage needs, which stage owns failure handling, and where the caller observes the final result. thenApply maps a successful value to another value; when the function itself returns a stage, thenCompose flattens the dependent stage rather than producing a nested future. thenCombine combines two successful inputs. These are dependency relationships, not proof that work runs in parallel or in a particular order.
A stage can already be complete when a continuation is attached. Non-async dependent actions may execute on a thread completing the source or another caller of a completion method under CompletableFuture’s documented policy. Async variants without an explicit executor normally use the common pool subject to the API’s documented exception; an explicit executor makes the scheduling resource and its owner visible. Avoid blocking a scarce worker on work that needs the same saturated executor. A dependency graph and a capacity budget should be reviewed together.
Define exceptional and recovery paths
A failed stage normally propagates exceptional completion to dependent stages that require its successful result. handle sees either a result or an exception and may compute a replacement; exceptionally computes a replacement only for exceptional completion. Recovery is a domain decision, not a way to make every chain look successful. A missing optional decoration might have a documented default, while a failed payment or authorization decision should remain visible unless the contract defines a safe recovery. Test both allowed recovery and a failure that must propagate.
whenComplete observes an outcome and normally preserves it rather than computing a replacement. Its own failure has precedence rules: if the source already failed, the source failure is preferred; if the source succeeded and the observer fails, the dependent stage fails with the observer’s exception. A normal result may itself be null, so inspect the exception argument rather than treating a null value as proof of failure. join reports exceptional completion through CompletionException in the usual exceptional case, while get uses its checked waiting and ExecutionException contract. Cancellation has its own CancellationException behavior.
Separate timeout, cancellation, and external effects
A timeout is a boundary on waiting or on a stage’s completion policy; it does not undo work already done by a remote service. CompletableFuture.orTimeout completes that same future exceptionally if it has not otherwise completed before the timeout; it is not a universal cancellation mechanism for the underlying operation. Completing a future exceptionally or canceling a CompletableFuture does not by itself guarantee interruption of the computation that might eventually complete it. Define task ownership and operation-specific cancellation separately.
If a charge, database commit, or notification may have succeeded before a timeout, preserve a stable operation identity and follow the external system’s documented status, idempotency, or reconciliation protocol. Do not retry a non-idempotent action blindly. A copied future can help isolate a timeout policy from another observer’s future state, but it still does not stop underlying work. Test the stage outcome and the actual task cleanup or external effect separately; a completed exceptional future is not proof that a resource has been released.
Own executor and resource lifecycles
When supplying an executor, define its owner, admission policy, queue bound, rejection behavior, and shutdown sequence. In Java 17 ExecutorService is not AutoCloseable, so the owner calls shutdown and awaits termination explicitly, with a bounded escalation policy. A stage can complete exceptionally when a dependent action fails or scheduling is rejected; observe the returned stage rather than assuming submission means success. Resource ownership inside tasks remains separate from executor ownership, and task cleanup must happen on both normal and exceptional paths.
The Java 17 walkthrough below uses an explicitly owned executor and already-controlled values. It attaches a non-blocking transformation to a supplied executor, observes completion with get, and shuts down in finally. The fragment is illustrative and not executed for this lesson. It does not prove a real service’s latency, cancellation, or cleanup; an actual system needs bounded admission, task-specific resource handling, and failure translation. Avoid attaching a heavyweight blocking action to a non-async continuation while holding a lock merely because it is concise.
import java.util.concurrent.*;
class StageWalkthrough {
static int calculate() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(1);
try {
CompletableFuture<Integer> source = CompletableFuture.completedFuture(4);
CompletableFuture<Integer> result = source.thenApplyAsync(n -> n * 2, executor);
return result.get(); // ExecutionException preserves the task cause
} finally {
executor.shutdown();
try {
if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
executor.shutdownNow();
if (!executor.awaitTermination(1, TimeUnit.SECONDS))
System.err.println("executor did not terminate");
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
// For this controlled value, a successful call returns 8.
}
This unexecuted fragment uses a synthetic value; the actual environment needs separate rejection, scheduling, and cleanup tests.
Control completion and interpret evidence
Controlled CompletableFutures let a test complete stages in a chosen order without sleeping. Test a successful transformation, a dependent-stage failure, an allowed recovery, and a failure that must not become a fallback. For allOf, inspect the aggregate outcome and, when needed, each component’s result; for either-style operations, do not assume the winner is a successful result unless the contract guarantees it. Independent stages can finish in either order unless the application adds an explicit dependency.
Use latches or gates when testing executor saturation or cleanup, and an outer timeout to prevent a hanging test. Ensure teardown releases test gates even after failure. A fake service demonstrates local composition and error mapping, not a real provider’s latency or transaction semantics. The worked examples below are illustrative Java 17 traces with explicit completion assumptions and are not executed programs. Record actual compiler, runtime, workload, and observed outcomes only when a complete test is genuinely run.
20 worked examples
1. Future-stage trace 1
Problem: Transform a completed value in this stated trace?
- The source stage is already complete with 5.
- The mapper doubles it to 10.
completedFuture(5).thenApply(n -> n*2)
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: result=10
Why this result follows: The stage relationship does not imply a new thread.
2. Future-stage trace 2
Problem: Identify a nested stage in this stated trace?
- The mapping function returns a CompletableFuture<Integer>.
- thenApply wraps that returned future as its result.
completedFuture(5).thenApply(n -> completedFuture(n+1))
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: CompletableFuture<CompletableFuture<Integer>>
Why this result follows: The result shape contains an additional stage.
3. Future-stage trace 3
Problem: Flatten a dependent stage in this stated trace?
- The function returns a stage containing 6.
- thenCompose connects that stage as the dependent result.
completedFuture(5).thenCompose(n -> completedFuture(n+1))
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: CompletableFuture<Integer> completing with 6
Why this result follows: The composed result has one stage layer.
4. Future-stage trace 4
Problem: Trace two dependent transformations in this stated trace?
- The first transformation changes 2 to 5.
- The second receives 5 and produces 10.
completedFuture(2).thenApply(n -> n+3).thenApply(n -> n*2)
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: result=10
Why this result follows: Dependency order follows the stage chain.
5. Future-stage trace 5
Problem: Combine two successful values in this stated trace?
- Both source stages are already complete.
- The combiner adds 6 and 4.
completedFuture(6).thenCombine(completedFuture(4),Integer::sum)
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: result=10
Why this result follows: This demonstrates value flow, not measured parallelism.
6. Future-stage trace 6
Problem: Interpret aggregate completion after both stages finish.
- allOf waits for the supplied stages to complete.
- An exceptional component causes exceptional aggregate completion.
allOf(a,b); // a completes normally; b later completes exceptionally
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: allOf completes exceptionally after the stated completions
Why this result follows: Inspect individual stages when their separate results matter.
7. Future-stage trace 7
Problem: Interpret the first completed outcome.
- anyOf completes when one input completes.
- The first completion in this fixture is exceptional.
anyOf(a,b); // a completes exceptionally first; b later succeeds
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: aggregate completes exceptionally
Why this result follows: First completion is not necessarily first success.
8. Future-stage trace 8
Problem: Trace propagation through a success-only stage.
- The source has no successful value.
- The dependent transformation is not applied normally and the dependent stage fails.
failedFuture(new IllegalStateException()).thenApply(n -> n)
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: exceptional dependent completion
Why this result follows: A success mapper is not a failure handler.
9. Future-stage trace 9
Problem: Trace an explicitly allowed fallback.
- The source completes exceptionally.
- The recovery function supplies zero under this fixture’s policy.
failedFuture(new IllegalStateException()).exceptionally(e -> 0)
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: normal result 0
Why this result follows: Recovery is valid only when the domain permits that substitute.
10. Future-stage trace 10
Problem: Trace handle on normal completion.
- The source result is 5 and exception argument is null.
- The success branch returns 6.
completedFuture(5).handle((v,e) -> e==null ? v+1 : 0)
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: normal result 6
Why this result follows: handle can inspect both outcome channels.
11. Future-stage trace 11
Problem: Determine exceptional-completion precedence in this stated trace?
- The source was already exceptional with E.
- whenComplete gives the source failure preference in this case.
failed source E; whenComplete observer also throws F
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: dependent stage retains source failure E
Why this result follows: Observation is not unconditional replacement of an existing failure.
12. Future-stage trace 12
Problem: Observe failure through join in this stated trace?
- The stage is completed exceptionally.
- join reports the failure through an unchecked completion wrapper.
failedFuture(new IllegalStateException()).join()
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: CompletionException with IllegalStateException cause
Why this result follows: The caller must observe and interpret the cause.
13. Future-stage trace 13
Problem: Assess continuation execution context in this stated trace?
- The continuation depends on source completion.
- A non-async action may run in the completing thread or another permitted caller.
source.complete(5); // non-async thenApply attached; completion occurs on worker W
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: do not assume a dedicated new thread
Why this result follows: Execution policy is distinct from dependency order.
14. Future-stage trace 14
Problem: Identify scheduling ownership in this stated trace?
- The async continuation is arranged through the supplied executor.
- Its owner must define admission and shutdown.
thenApplyAsync(mapper, executor); // explicitly owned executor
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: explicit executor policy applies
Why this result follows: Supplying an executor does not remove failure handling.
15. Future-stage trace 15
Problem: Trace a stage timeout in this stated trace?
- The deadline expires before f completes in the fixture.
- orTimeout completes that same future exceptionally with TimeoutException.
f.orTimeout(1,SECONDS); // f remains incomplete until timeout
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: f completes exceptionally with TimeoutException
Why this result follows: The timeout is not proof that underlying work stopped.
16. Future-stage trace 16
Problem: Assess cancellation and work in this stated trace?
- CompletableFuture cancellation is exceptional completion of the future.
- The underlying operation is not guaranteed to stop by that state change.
CompletableFuture f; f.cancel(true); // underlying task ignores any separate cancellation
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: future canceled; task may continue
Why this result follows: Task-specific cancellation and cleanup need separate ownership.
17. Future-stage trace 17
Problem: Diagnose a capacity cycle in this stated trace?
- A occupies the only worker while waiting.
- B cannot start from the same executor’s queue.
single-worker executor: task A submits task B to same executor and blocks waiting for B
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: starvation or deadlock until an external change
Why this result follows: Compose or redesign the execution boundary to avoid the blocking cycle.
18. Future-stage trace 18
Problem: Interpret completion ordering in this stated trace?
- Neither stage depends on the other in the stated graph.
- B can complete before A despite submission order.
stage A and stage B are independent; B completes first in this trace
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: B then A is possible
Why this result follows: Independent stages have no general completion-order guarantee.
19. Future-stage trace 19
Problem: Classify a normal null result.
- The source completes normally with null.
- The exception argument is null, so the success branch is selected.
completedFuture(null).handle((v,e) -> e==null ? "success" : "failure")
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: result="success"
Why this result follows: A null value alone does not establish exceptional completion.
20. Future-stage trace 20
Problem: Assess failure observation and disclosure.
- The stage failure must be observed at the boundary.
- The complete public response body contains only the stable category failed, so it omits the synthetic token.
fake stage fails with synthetic token in exception; public response body contains only stable category "failed"
This trace depends on the stated completion assumptions; no asynchronous program was executed for this example.
Expected result: failure reported; token not exposed publicly
Why this result follows: Restricted diagnostics and public output have distinct contracts.
Common errors and fixes
A future contains another future
- Why it happens
- A future-returning function was transformed without flattening.
- How to fix it
- Use thenCompose when a flattened stage is intended.
- Prevent it next time
- Review the resulting generic type.
Failure becomes an unexplained success
- Why it happens
- A handler always returned a fallback.
- How to fix it
- Apply recovery only when the domain permits it.
- Prevent it next time
- Test propagated failure.
Tasks remain after the operation
- Why it happens
- Executor ownership was not defined.
- How to fix it
- Shut down an owned executor and handle tasks.
- Prevent it next time
- Test lifecycle and shutdown.
20 practice exercises
1. What does the first stage produce?
Show hint
The stage begins with 21 and applies multiplication once.
Show worked solution
It produces 42 by multiplying the completed value 21 by two.
thenApply transforms the completed value 21 into 42 by doubling it. The example does not prove a new thread starts because the source is complete and the continuation is non-async.
Check your solution
- The stage result is 42.
- No thread order or parallelism is inferred from that value.
2. Why might a fallback be inappropriate after a failure?
Show hint
Does the domain contract permit converting this failure to a normal result?
Show worked solution
A default can hide a failure that the caller must know about. Preserve the error unless the contract explicitly permits recovery.
A fallback can hide a failure the caller must know about or produce misleading success. Recover only for cases allowed by the contract, and test another failure that must remain exceptional with its cause preserved.
Check your solution
- Fallback is limited to the permitted case.
- A nonrecoverable failure remains observable.
3. A lookup function returns a future that fails after thenApply has returned it. Why can observing only the outer future miss the failure, and how can a flattened chain expose it?
Show hint
The outer and inner stages have separate completion states.
Show worked solution
With thenApply the outer future can complete normally with a reference to an inner future that later fails; observing only the outer success misses that failure. Use thenCompose to represent the dependent lookup as one stage, then assert its exceptional completion and cause with a controlled failed lookup.
Check your solution
- The nested outer stage can succeed while the inner stage fails.
- The flattened stage exposes the dependent failure.
4. Two independent quote stages return 6 and 4. Design a combination and a failure control without claiming execution order.
Show hint
The combiner needs both successful inputs.
Show worked solution
Use thenCombine to produce 10 after both succeed. In a separate case fail one stage and assert the combined result is exceptional; do not assert which independent task finishes first.
Check your solution
- The successful combination returns 10.
- A failed input produces an observed failure.
5. Three futures feed allOf; one fails and the other two complete later. What should a test observe before inspecting individual results?
Show hint
The aggregate and component outcomes are different observations.
Show worked solution
Complete all three controlled futures and assert allOf completes exceptionally. Then inspect each component separately to identify successes and failures; do not assume allOf returns their values or stops remaining work.
Check your solution
- The aggregate is exceptional after the supplied stages complete.
- Individual outcomes are inspected separately.
6. Two replicas may succeed or fail independently. Design a first-success coordinator that also terminates when both fail, and specify what happens to remaining work.
Show hint
A first completion primitive alone does not express this policy.
Show worked solution
Track both controlled outcomes: complete with the first successful value; if both fail, complete exceptionally with a documented diagnostic. Define whether remaining work is canceled or allowed to finish, and separately observe its cleanup. Test failure-then-success, success-then-failure, and both-fail orders.
Check your solution
- Either successful replica can provide the result after an earlier failure.
- Both failures produce a terminal failure and remaining-work policy is explicit.
7. A profile decoration may fall back to "unknown" on a documented not-found failure, but authorization failure must propagate. Design a recovery test matrix.
Show hint
Recovery depends on the domain failure.
Show worked solution
Configure a controlled stage to fail with not-found and assert the permitted fallback, then fail with authorization error and assert it remains exceptional. Include a normal profile control so the handler cannot always return the fallback.
Check your solution
- Only the documented not-found case recovers.
- Authorization failure remains observable.
8. A whenComplete observer throws F after a source succeeds; in another case source failure E precedes observer failure F. Compare outcomes.
Show hint
The source failure has preference when both fail.
Show worked solution
After a successful source, the observer’s F makes the dependent stage exceptional. When the source already failed with E and the observer also throws F, the source exceptional completion is preferred; test both cases.
Check your solution
- Observer failure turns a successful source into failure.
- The original source failure is preferred when both fail.
9. A failed future is observed once with get and once with join. Compare failure reporting and waiting-thread interruption.
Show hint
The two methods expose different waiting contracts.
Show worked solution
get reports task failure through ExecutionException and may throw InterruptedException while waiting; join normally reports exceptional completion through CompletionException. Test the underlying cause and handle interruption under the caller’s policy rather than treating wrappers as identical.
Check your solution
- Both paths preserve an inspectable cause for ordinary exceptional completion.
- The get waiting path handles InterruptedException.
10. A thread completes a future while holding lock M; a non-async continuation also needs M and performs expensive work. What should a design review consider?
Show hint
A non-async action may run in the completing thread.
Show worked solution
Do not assume the continuation gets a new thread or that expensive work under the completing context is harmless. Move the work to an appropriately owned executor or restructure lock scope, preserve the invariant, and test completion without a lock cycle.
Check your solution
- The execution policy is explicit.
- The invariant is preserved without a blocking lock cycle.
11. An async stage uses a bounded executor with one worker and one queue slot. Both are occupied. Design a rejection and lifecycle test.
Show hint
Executor policy determines admission.
Show worked solution
Configure the stated executor with AbortPolicy, gate the worker, fill the queue, and submit the continuation under test. Assert rejection or exceptional stage behavior at the documented boundary, then release gates and shut down the owned executor.
Check your solution
- Saturation produces the configured observable rejection.
- The executor is terminated or a failed shutdown is reported.
12. A remote charge may complete after orTimeout fires. Define separate stage, task, and business-outcome assertions.
Show hint
Exceptional future completion does not undo external work.
Show worked solution
Assert the timed stage completes exceptionally, then use a separate task or provider signal to learn whether work finished. Reconcile the stable operation ID using the provider’s documented protocol before retrying; test both accepted and not-accepted synthetic outcomes.
Check your solution
- The timeout stage and actual task completion are observed separately.
- An uncertain charge is reconciled before an unprotected retry.
13. A CompletableFuture is canceled with mayInterruptIfRunning=true. Does that guarantee the underlying computation is interrupted and its resource closed?
Show hint
CompletableFuture cancellation is exceptional completion, not direct task control.
Show worked solution
No. The API does not use the flag to control interruption in this class. Design operation-specific cancellation and observe task exit and resource closure separately; test a cooperative and a noncooperative synthetic task.
Check your solution
- Canceled future state is not treated as proof of interruption.
- Resource closure has separate evidence.
14. Every worker in a two-thread executor blocks on a child stage scheduled to the same executor. Explain the risk and a repair.
Show hint
The dependent work needs capacity held by its waiters.
Show worked solution
Both children can remain queued while both workers wait, producing starvation or deadlock. Compose stages without blocking those workers, or redesign executor boundaries and admission; test with controlled gates and bounded cleanup.
Check your solution
- The same-pool dependency cycle is identified.
- The repair avoids blocking all workers on queued children.
15. Two controlled futures feed thenCombine. Complete B with 4 while A remains pending, then complete A with 6. What should a test assert at each point?
Show hint
A combination requiring both values cannot compute from one alone.
Show worked solution
After B completes, assert the combined stage is still incomplete because A is pending. Complete A, then assert the combined sum is 10; repeat with the completion order reversed and assert the same result without asserting scheduler thread identity.
Check your solution
- The combined stage remains incomplete while A is pending.
- Both completion orders yield the combined result 10.
16. A stage completes normally with null and a handler uses v==null to identify failure. Repair the handler and test two cases.
Show hint
Normal results may be null.
Show worked solution
Use the exception argument to distinguish exceptional completion: a null exception means normal completion even if v is null. Test normal-null and an exceptional stage separately, with an explicit domain policy for null values.
Check your solution
- Normal null is not classified as an exception.
- The exceptional case follows its failure policy.
17. A stage failure message contains a synthetic token. Design public error and restricted diagnostic checks.
Show hint
Observing failure does not require exposing its raw message.
Show worked solution
Map the failure to a stable public category without the token, while preserving an appropriate cause in restricted diagnostics. Capture the full ordinary log and public response using a synthetic marker and assert neither leaks it.
Check your solution
- The public response omits the marker.
- Ordinary rendered logs omit the marker while failure remains observable.
18. Two callers share future f; one calls f.orTimeout. How can a timeout policy be isolated from the other observer’s future state?
Show hint
orTimeout completes the same future.
Show worked solution
Apply the timeout to a copy when the API and desired contract support that isolation, and test that the original can complete normally after the copy times out. The copy does not cancel or stop underlying work; define that policy separately.
Check your solution
- The timeout affects the timed copy in the controlled test.
- The original can still complete normally.
19. An owned Java 17 executor runs a stage that fails. Design a shutdown test that observes both the failure and termination.
Show hint
Result observation and executor lifecycle are separate.
Show worked solution
Observe the returned stage’s cause, then in finally shut down the executor and await termination under a bounded escalation policy. Use a synthetic failure and assert termination or report a failed shutdown; do not use try-with-resources for ExecutorService on Java 17.
Check your solution
- The stage failure is observed.
- The executor owner observes termination or reports failure.
20. A fake provider test passes normal composition, but the actual provider timeout and an unauthorized request are untested. Define a minimal evidence matrix.
Show hint
Local composition, remote failure, and authorization are separate boundaries.
Show worked solution
Keep the fake test for value flow. Add an isolated provider-boundary timeout test under the real client contract, an unauthorized request test with no protected effect, and an authorized success control; report which integration environments were actually exercised.
Check your solution
- The timeout and authorization boundaries have separate tests.
- The evidence does not infer real provider behavior from the fake.
Key takeaways
- Composition and execution policy are separate decisions.
- Make failure ownership and recovery explicit.
- Stage composition does not guarantee a new thread or independent-stage order.
- Fallbacks and exceptional stages need explicit domain policy.
- Future timeout or cancellation does not prove underlying work stopped or its effects were undone.