kap-core¶
The foundation module. Type-safe parallel orchestration with visible phases.
Depends on: kotlinx-coroutines-core only.
Platforms: JVM, JS (IR), WASM (JS), Linux X64, macOS (x64/ARM64), iOS (x64/ARM64/Simulator).
Tests: 477 tests across 40 test classes, including property-based algebraic law verification.
What kap-core solves¶
You have multiple async calls. Some parallel, some sequential. kap-core gives you .with for independent tasks, .then for barriers, and .andThen for dependent phases. The code shape becomes the execution plan.
With @KapTypeSafe (via the kap-ksp module), you get named builder methods generated from your data class properties — .with { user from }, .then { stock from }, etc. — making chains self-documenting while retaining full compile-time type safety. The generic .with {} / .then {} API shown throughout this page is the underlying core API; named builders are the recommended user-facing pattern built on top of it.
Level 1 — Learn First¶
.with — Independent tasks in parallel¶
@KapTypeSafe
data class Dashboard(val user: String, val cart: String, val promos: String)
val dashboard: Dashboard = kap(::Dashboard)
.with { user from fetchUser() } // ┐ all three start at t=0
.with { cart from fetchCart() } // │ total time = max(individual)
.with { promos from fetchPromos() } // ┘ swap any two? COMPILE ERROR
.evalGraph()
@KapTypeSafe generates .with { user from }, .with { cart from }, .with { promos from } from the data class properties. The generic .with {} API is equivalent but positional — named builders enforce the correct parameter at each step.
Troubleshooting .with compiler errors (4.3.0+)¶
.with is a small overload family on a curried receiver — Kap<(A) -> B>.with(Kap<A>) and Kap<(A) -> B>.with(suspend () -> A) — and the slot's argument must be a producer of A, never the plain value. The two classic mistakes are guarded by deprecations (issue #19), so they still fail to compile but with the fix in the message instead of the old wall of text:
You pass the plain value (.with(user) instead of .with { user }):
'fun <A, B> Kap<(A) -> B>.with(value: A): Kap<B>' is deprecated.
with() needs a producer of the slot's type, not the value itself.
Write `.with { value }` (lambda) or `.with(Kap { value })`.
Fix: .with { user } (lambda) or .with(Kap { user }) (explicit Kap, runs in parallel).
You pass a Kap (or value) of the wrong type — e.g. .with(Kap { 42 }) when the slot expects User:
'fun <A, B> Kap<(A) -> B>.with(wrong: Any?): Kap<B>' is deprecated.
with() takes a Kap<A> or a suspend lambda producing the slot's argument type A —
the type the next curried slot expects. The value you passed matches neither.
Fix: read the curried function's next parameter (that is A) and provide a producer of exactly that type.
Note the difference: a lambda with a wrong body gets a precise error (Return type mismatch: expected 'User', actual 'String') — prefer lambdas and you rarely see either guard. A non-function receiver (Kap.of(1).with { ... } — the left side is not a curried function) is still reported as Candidate ... is inapplicable because of a receiver type mismatch; the fix is to start from a curried function (Kap.of { a -> { b -> ... } }, kap(::Result) with @KapTypeSafe, or Kap.of(::twoArgFn)). Long-term option (out of scope here): a compiler plugin emitting custom diagnostics for these cases; the deprecation guards cover the common slips today.
.then — Phase barrier¶
.then creates an explicit synchronization point. Everything above must complete before anything below starts.
.andThen — Dependent phase¶
// Phase 1
val ctx = coroutineScope {
val dProfile = async { fetchProfile(userId) }
val dPrefs = async { fetchPreferences(userId) }
val dTier = async { fetchLoyaltyTier(userId) }
UserContext(dProfile.await(), dPrefs.await(), dTier.await())
}
// Phase 2 — needs ctx
val enriched = coroutineScope {
val dRecs = async { fetchRecommendations(ctx.profile) }
val dPromos = async { fetchPromotions(ctx.tier) }
val dTrending = async { fetchTrending(ctx.prefs) }
val dHistory = async { fetchHistory(ctx.profile) }
EnrichedContent(dRecs.await(), dPromos.await(), dTrending.await(), dHistory.await())
}
// Phase 3 — needs both
val dashboard = coroutineScope {
val dLayout = async { renderLayout(ctx, enriched) }
val dTrack = async { trackAnalytics(ctx, enriched) }
FinalDashboard(dLayout.await(), dTrack.await())
}
// With @KapTypeSafe on UserContext, EnrichedContent, and FinalDashboard
val dashboard: FinalDashboard = kap(::UserContext)
.with { profile from fetchProfile(userId) } // ┐
.with { preferences from fetchPreferences(userId) } // ├─ phase 1
.with { loyaltyTier from fetchLoyaltyTier(userId) } // ┘
.andThen { ctx -> // ── barrier: ctx available
kap(::EnrichedContent)
.with { recommendations from fetchRecommendations(ctx.profile) } // ┐
.with { promotions from fetchPromotions(ctx.tier) } // ├─ phase 2
.with { trending from fetchTrending(ctx.prefs) } // │
.with { history from fetchHistory(ctx.profile) } // ┘
.andThen { enriched -> // ── barrier
kap(::FinalDashboard)
.with { layout from renderLayout(ctx, enriched) } // ┐ phase 3
.with { analytics from trackAnalytics(ctx, enriched) } // ┘
}
}
.evalGraph()
val dashboard: FinalDashboard = kap(::UserContext)
.with { fetchProfile(userId) } // ┐
.with { fetchPreferences(userId) } // ├─ phase 1
.with { fetchLoyaltyTier(userId) } // ┘
.andThen { ctx -> // ── barrier: ctx available
kap(::EnrichedContent)
.with { fetchRecommendations(ctx.profile) } // ┐
.with { fetchPromotions(ctx.tier) } // ├─ phase 2
.with { fetchTrending(ctx.prefs) } // │
.with { fetchHistory(ctx.profile) } // ┘
.andThen { enriched -> // ── barrier
kap(::FinalDashboard)
.with { renderLayout(ctx, enriched) } // ┐ phase 3
.with { trackAnalytics(ctx, enriched) } // ┘
}
}
.evalGraph()
24 lines of nested coroutineScope/async/await vs 14 lines of flat chain. The dependency graph is the code shape.
Level 2 — Common Patterns¶
Composition styles¶
zip and combine support arities 2-22.
Partial failure¶
Use this when: one service can fail but you still want the rest.
// supervisorScope is manual and error-prone
val result = supervisorScope {
val dUser = async { fetchUserMayFail() }
val dCart = async { fetchCartAlways() }
val dConfig = async { fetchConfigAlways() }
val user = try { dUser.await() } catch (e: Exception) { "anonymous" }
val cart = dCart.await()
val config = dConfig.await()
PartialDashboard(user, cart, config)
}
Without settled — one failure cancels everything:
@KapTypeSafe
data class Dashboard(val user: String, val cart: String, val config: String)
val dashboard = kap(::Dashboard)
.with { user from fetchUser() } // throws! → cart and config CANCELLED
.with { cart from fetchCart() } // never runs
.with { config from fetchConfig() } // never runs
.evalGraph()
// RuntimeException — entire dashboard lost. Cart and config were fine.
With settled { } — failure wrapped, siblings continue:
// The type changes: user becomes Result<String> instead of String
@KapTypeSafe
data class Dashboard(val user: Result<String>, val cart: String, val config: String)
val dashboard = kap(::Dashboard)
.with(DashboardKap.user from settled { fetchUser() }) // Result<String> — won't cancel siblings
.with { cart from fetchCart() } // String — runs normally
.with { config from fetchConfig() } // String — runs normally
.evalGraph()
// Dashboard(user=Result.failure(RuntimeException), cart=cart-ok, config=config-ok)
// Use the result with a fallback:
val userName = dashboard.user.getOrDefault("anonymous") // "anonymous"
Since 4.1.0 settled (and every other CONVERT/RETRY operator) runs its operand inside its own coroutineScope, so a failure inside a nested parallel graph (traverse/with/zip children) is converted to Result.failure too instead of cancelling the surrounding chain — the Isolation law (see error semantics). The escape hatch Kap<A>.isolated() applies the same scope boundary to any graph you hand to a third party.
timed { } — Measure any call without manual instrumentation¶
The timed { } shorthand wraps a call so it returns TimedResult<A> — the value plus its wall-clock duration:
@KapTypeSafe
data class Dashboard(val user: String, val latency: TimedResult<String>)
val dashboard = kap(::Dashboard)
.with { user from fetchUser() }
.with(DashboardKap.latency from timed { fetchSlowService() }) // TimedResult(value, duration)
.evalGraph()
println(dashboard.latency.duration) // 230.ms
println(dashboard.latency.value) // "slow-result"
Like settled { }, timed { } is a top-level shorthand for Kap { block() }.timed(). Use it inline in .with calls to measure individual branches without restructuring your graph.
traverseSettled — Collect ALL results, no cancellation¶
Collections¶
Use this when: you have a list of items to process in parallel with bounded concurrency.
traverse¶
traverseDiscard — Fire-and-forget¶
sequence / sequence(concurrency)¶
Error handling¶
Use this when: you need fallbacks, timeouts, or retries.
.timeout(duration, default)¶
.timeoutAsFailure(duration) — a timeout that retry/recover can handle¶
timeout(duration) fails with TimeoutCancellationException, which is a CancellationException — and by law every retry rethrows cancellations, so timeout(d).retry(...) never retries a slow call. Use timeoutAsFailure(d) when the timeout should be an ordinary failure (KapTimeoutException) that retry, recover and settled can handle:
val result = Kap { fetchSlowService() }
.timeoutAsFailure(2.seconds) // KapTimeoutException, not a cancellation
.retry(Schedule.times<Throwable>(3)) // retries slow calls too (kap-resilience)
.evalGraph()
There is also a timeout(duration, fallback: Kap<A>) overload that runs a fallback graph on expiry.
.recover { } / .recoverWith { }¶
.retry(maxAttempts, delay, backoff)¶
Simple retry (for composable Schedule-based retry, see kap-resilience):
.ensure(error) { predicate } / .ensureNotNull(error) { extract }¶
catching { } — Exception-safe Result¶
.orElse(other) / firstSuccessOf¶
Racing¶
Use this when: you want the first success from multiple sources (an early failure does not win — it only surfaces when every racer fails, accumulated as suppressed exceptions).
raceN(c1, c2, ..., cN) — First to succeed wins, rest cancelled¶
race(fa, fb) — Two-way race¶
raceAll(list) — Race a dynamic list¶
Level 3 — Advanced¶
Construction utilities¶
Kap { } — Wrap a suspend lambda¶
val effect: Kap<String> = Kap { fetchUser() } // nothing runs yet
val result: String = effect.evalGraph() // NOW it runs
kap(f) — Curry a function for .with chains¶
Works with constructor refs, function refs, and lambdas:
// Constructor reference
@KapTypeSafe
data class Greeting(val name: String, val message: String)
val g1 = kap(::Greeting).with { name from fetchName() }.with { message from "hello" }.evalGraph()
// Lambda — use Kap.of with manual currying
val greet: (String, Int) -> String = { name, age -> "Hi $name, you're $age" }
val g2 = Kap.of { name: String -> { age: Int -> greet(name, age) } }
.with { fetchName() }.with { fetchAge() }.evalGraph()
// Function — annotate with @KapTypeSafe for named builders
@KapTypeSafe
fun buildSummary(name: String, items: Int): String = "$name has $items items"
val g3 = kap(::buildSummary).with { name from fetchName() }.with { items from 5 }.evalGraph()
Kap.of(value) / Kap.empty / Kap.failed(error) / Kap.defer { }¶
of, empty, failed and defer are companion members (since 4.1.0) — no import kap.of needed:
val pure: Kap<Int> = Kap.of(42) // pure value
val unit: Kap<Unit> = Kap.empty // Unit computation
val failed: Kap<Nothing> = Kap.failed(RuntimeException("boom")) // wrapped failure
val lazy: Kap<String> = Kap.defer { Kap { expensiveSetup() } } // lazy construction
.thenValue¶
Unlike .then which creates a real barrier, .thenValue fills a slot sequentially without blocking parallel siblings:
@KapTypeSafe
data class Page(val content: Content, val sidebar: Sidebar, val timestamp: Timestamp)
val result = kap(::Page)
.with { content from fetchContent() } // parallel
.with { sidebar from fetchSidebar() } // parallel
.thenValue { timestamp from computeTimestamp() } // sequential fill, no barrier
.evalGraph()
Flow integration¶
Flow.mapKapOrdered — Preserve upstream order¶
// channelFlow + manual index tracking to preserve order
val results: Flow<String> = channelFlow {
val buffer = ConcurrentHashMap<Int, String>()
var nextIndex = 0
val semaphore = Semaphore(5)
userIdFlow.collectIndexed { index, id ->
semaphore.acquire()
launch {
val result = fetchUser(id)
buffer[index] = result
semaphore.release()
// Flush in-order results... (complex bookkeeping)
}
}
}
Flow.firstAsKap()¶
Memoization¶
// Manual Mutex + double-checked locking
private val mutex = Mutex()
private var cached: String? = null
suspend fun fetchOnce(): String {
cached?.let { return it }
return mutex.withLock {
cached?.let { return it }
val result = expensiveCall()
cached = result
result
}
}
// Caches failures too. Transient error? Cached forever.
Shared state — Ref (4.3.0)¶
Ref<A> is the typed atomic mutable reference for the shared state that does not need STM: every operation runs under a Mutex, so concurrent updates never lose writes, and cancellation while waiting for the lock leaves the value untouched.
val counter = Ref.of(0).evalGraph() // a Kap builds the reference
val graph = Kap.of { a: Int -> { b: Int -> a + b } }
.with { counter.update { it + 1 } } // atomic read-modify-write
.with { counter.update { it + 1 } }
graph.evalGraph()
// counter.get().evalGraph() == 2
| Operation | Effect |
|---|---|
get(): Kap<A> |
reads the current value |
set(a): Kap<Unit> |
replaces it |
update { a -> a' }: Kap<A> |
atomic transform, returns the new value |
modify { a -> next to result }: Kap<B> |
general read-modify-write with a separate result |
The function passed to update/modify must be pure, fast and must not call back into the same Ref (that would deadlock — the mutex is not reentrant).
Non-suspending state — SyncCell / Ref.sync¶
Ref operations are Kaps over a Mutex, so every read and write is a suspension point. An SPI that cannot suspend — KapTracer.onEvent, a listener, a shutdown hook — gets the same state as a SyncCell: a lock-free atomic register (compare-and-set, no coroutines, no lock) with the Ref value semantics.
class Metrics : KapTracer {
private val events = Ref.sync(0) // or SyncCell.of(0)
override fun onEvent(event: TraceEvent) {
val previous = events.getAndUpdate { it + 1 } // atomic; returns the previous count
if (previous == 0) log.firstEvent(event)
}
}
| Operation | Effect |
|---|---|
get(): A |
reads the current value |
set(a: A) |
replaces it |
update { a -> a' }: A |
atomic transform, returns the new value |
getAndUpdate { a -> a' }: A |
atomic transform, returns the previous value |
modify { a -> next to result }: B |
general read-modify-write with a separate result |
Laws (SyncCellTest, real threads and latches, no sleeps): concurrent updates never lose a write (N threads × M increments leave N * M), every previous value is handed out exactly once, a compare-and-set idiom claims its value exactly once, reads observe whole values, and a throwing transform leaves the cell untouched. The transform may be re-invoked under contention, so it must be pure and must not call back into the same cell.
Interop¶
Deferred.toKap() / Kap.toDeferred(scope)¶
Bridge between existing coroutine code and KAP. Useful when you have a Deferred from a library or legacy code and want to compose it with other Kap combinators (.map, .recover, .timeout, parallel .with chains, etc.).
val deferred: Deferred<String> = scope.async { fetchUser() }
val kap: Kap<String> = deferred.toKap()
val result = kap.evalGraph()
(suspend () -> A).toKap()¶
computation { } — Imperative builder¶
Observability¶
@KapTypeSafe
data class Dashboard(val user: String, val config: String)
val tracer = KapTracer { event ->
when (event) {
is TraceEvent.Started -> logger.info("${event.name} started")
is TraceEvent.Succeeded -> metrics.timer(event.name).record(event.duration)
is TraceEvent.Failed -> logger.error("${event.name} failed", event.error)
}
}
val result = kap(::Dashboard)
.with(DashboardKap.user from Kap { fetchUser() }.traced("fetch-user", tracer))
.with(DashboardKap.config from Kap { fetchConfig() }.traced("fetch-config", tracer))
.evalGraph()
Metrics — the Meter SPI¶
Meter is the small multiplatform seam between KAP code and any metrics
registry: counters by name+tags, timers that take the call, gauges read at
scrape time. Meter.Noop is the strict OFF value: the block runs bare, with
no clock read and zero allocation.
val meter: Meter = if (metricsEnabled) MicrometerMeter(registry) else Meter.Noop
meter.increment("poller.cycles")
meter.increment("turns.sealed", Tags.of("outcome" to "failed"))
// timed operations take the call — the OFF meter just runs it
val answer = meter.time("brain.request") { brain.ask(prompt) }
// gauges are read at scrape time, never cached
meter.gauge("outbox.depth", Tags.of("lane" to "main")) { outbox.depth().toDouble() }
Instrumentation must never break the measured code. Wrap a foreign implementation once so a throwing meter is reported (never silently swallowed) while the measured block's value and exception pass through untouched:
val meter = Meter.guarded(MicrometerMeter(registry)) { failure ->
log.warn("metrics failure in ${failure.operation} ${failure.name}", failure.error)
}
Build Tags values once at wiring time and reuse them on the hot path. The
SPI ships with its laws (MeterLawsTest): the no-op is inert, tags never
rewrite the metric name, a throwing meter cannot affect the block, and a timed
suspend block records exactly once under cancellation. The optional
kap-micrometer module implements the SPI over a Micrometer MeterRegistry.
Utilities¶
.keepFirst / .keepSecond¶
Run both in parallel, keep only one result:
.discard() / .peek { }¶
val unit = Kap { fetchUser() }.discard().evalGraph() // runs but returns Unit
val user = Kap { fetchUser() }
.peek { println("Fetched: $it") } // side-effect, returns original value
.evalGraph()
.on(context) / .named(name)¶
val result = Kap { readFile() }
.on(Dispatchers.IO) // switch dispatcher
.named("file-read") // coroutine name for debugging
.evalGraph()
.evalGraph() — Execute from any suspend context¶
delayed(duration, value) / .withOrNull(fa)¶
val result = delayed(100.milliseconds, "delayed-value").evalGraph()
// withOrNull fills a NULLABLE slot of a curried function — passes null when the Kap is null
val insurance: Kap<String>? = null
val booking = kap(::Booking) // Booking(flight: String, insurance: String?)
.with { flight from fetchFlight() }
.withOrNull(insurance) // insurance slot gets null, no launch
.evalGraph()
Execution model¶
Kap<A> is lazy — nothing runs until .evalGraph():
@KapTypeSafe
data class Dashboard(val user: String, val cart: String, val promos: String)
val plan: Kap<Dashboard> = kap(::Dashboard)
.with { user from fetchDashUser() }
.with { cart from fetchDashCart() }
.with { promos from fetchDashPromos() }
println("Plan built. Nothing has executed yet.")
println("plan is: ${plan::class.simpleName}")
val result: Dashboard = plan.evalGraph() // NOW it runs
Key guarantees:
- Structured concurrency: All parallel branches run inside
coroutineScope. One fails → siblings cancel. - Cancellation safety:
CancellationExceptionis never caught. All combinators re-throw it. - Context propagation:
withContext(MDCContext()) { graph.evalGraph() }propagates context to all branches (evalGraph()takes no arguments); thecontextKap captures the caller's context inside a graph. - No reflection: All type safety is compile-time. Zero runtime overhead.
- Algebraic laws: Functor, Applicative, Monad — property-tested via Kotest. See LAWS.md.
API Reference Map¶
| I want to... | Use this |
|---|---|
| Run tasks in parallel (named) | .with { paramName from } via @KapTypeSafe |
| Run tasks in parallel (generic) | .with { } |
| Wait for all before continuing | .then { } / .then { paramName from } |
| Use previous result in next phase | .andThen { ctx -> } |
| Handle one failure without cancelling rest | settled { } |
| Process a list with bounded concurrency | traverse(concurrency) { } |
| Retry on failure | .retry(maxAttempts, delay = …) (core) / .retry(schedule) (kap-resilience) |
| Timeout with fallback | .timeout(duration, default) |
| Timeout that retry can handle | .timeoutAsFailure(duration) |
| Recover from errors | .recover { } |
| Race multiple sources | raceN(c1, c2, c3) |
| Cache computation result | .memoizeOnSuccess() |
| Guaranteed resource cleanup | bracket(acquire, use, release) |