Skip to main content

fsharp-async-composition

Compose F# Task, Async, and ValueTask code with the correct semantics and builder (task, async, valueTask, cancellableTask, taskResult). Covers hot and cold start, boundary conversion, cancellation flow, exception wrapping, and ValueTask values read twice. Also covers FS0193, FS3501, and FS3511. Use when F# code mixes Task and Async, or returns or consumes ValueTask. Also use when code passes a CancellationToken, starts fire-and-forget work, or changes its async type.

v1.0.0New

Unsigned, install at your own risk

Unverified

This skill has no cryptographic signature attached. We can't verify the contents match what the publisher intended.

Install this skill

No account required. Pick your tool, or use the command that detects it for you.

Run in your terminal. It detects your AI tool.

npx @skills-hub-ai/cli install fsharp-skills-fsharp-async-composition
Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/fsharp-skills-fsharp-async-composition/SKILL.md

Setup guide →
0Save

Instructions

F# async composition

Most defects in this area compile. The code runs, but cancellation does not reach the work,
an Async never starts, a ValueTask is read twice, or an exception changes type. Choose the
builder from the boundary type, convert once at the boundary, and pass the token explicitly.

Builder choice

SituationUse
Code returns Task or Task<'T> to .NET callers (ASP.NET, interfaces, libraries)task { }
Interface or hot path returns ValueTask<'T>valueTask { } from IcedTasks, or task { } then ValueTask<'T>(t) at the edge
Work must be re-runnable or retried, or the token must flow implicitlyasync { }
Task-based code that must pass a token to bound Async and CancellableTask valuescancellableTask { } from IcedTasks
Task<Result<_,_>>taskResult { } from FsToolkit.ErrorHandling

FSharp.Core has task and async, but no valueTask builder. If the code does not open
IcedTasks, valueTask { } gives FS0039. FS0193 between ValueTask<'T> and Task<'T>,
or between Task<'T> and Async<'T>, means the builder does not match the declared return
type. Change the builder or convert once. Do not add a conversion at each call site.

Hot and cold

  • task and valueTask are hot. The body runs up to the first incomplete await when you call
    the function. A Task value is a running operation, not a recipe. To retry, take
    unit -> Task<'T>, not Task<'T>.
  • async is cold. Nothing runs until Async.Start, Async.StartAsTask,
    Async.RunSynchronously, or a let!. work |> ignore on an Async drops the work, and the
    compiler does not warn.
  • Async.AwaitTask(api.Get x) calls api.Get when the Async value is built, not when it
    runs. A retry of that value awaits the same failed task again. Build the task inside the
    body: async { return! Async.AwaitTask(api.Get x) }.
  • Fire-and-forget: Async.Start(work, ct) for Async, or work () |> ignore for a hot
    Task. Put an exception handler inside the work. An unhandled exception in Async.Start
    work is rethrown on a thread-pool thread and stops the process. Never ignore an Async value.

Conversion at boundaries

FromToUseNote
Async<'T>Task<'T>Async.StartAsTask(work, cancellationToken = ct)Always pass the token.
Async<'T>Task<'T> on the caller's threadAsync.StartImmediateAsTask(work, ct)Same token rule.
Task<'T>Async<'T>Async.AwaitTask tFaults arrive as AggregateException.
ValueTask<'T>Task<'T>vt.AsTask() onceAfter this, await only the Task.
Task<'T>ValueTask<'T>ValueTask<'T>(t)
Async<'T> inside tasklet! x = workRuns on Async.DefaultCancellationToken, not the caller's token.

Do not block: .Result, .Wait(), GetAwaiter().GetResult(), and
Async.RunSynchronously hold a thread, throw at the call instead of in the returned task, and
.Result and .Wait() wrap the exception in AggregateException. Do not use
ContinueWith(...).Unwrap() in F#. task { let! x = t ... } composes directly.

Cancellation

A CancellationToken parameter that the body does not pass on is a defect. The tests still pass.

  • task { let! x = someAsync } ignores the function's ct. Start the Async with
    Async.StartAsTask(work, cancellationToken = ct), or write the body as async and convert at
    the edge, or use cancellableTask and bind the Async inside it.
  • Pass ct to every .NET call that accepts one: Task.Delay(ms, ct), stream.ReadAsync(buffer, ct).
  • Inside async, Async.CancellationToken reads the token. Async.Sleep and let! check it.
  • Async.StartChild does not cancel a sibling when another child fails. Async.Parallel does.
    The sibling stops only if its .NET call received the token from Async.CancellationToken.
    CancellationToken.None in a child means a failure cannot stop it.
let handle (lib: Library) (id: int) (ct: CancellationToken) : Task<Report> =
    let work =
        async {
            let! report = buildReport lib id
            let audit =
                async {
                    try
                        do! lib.Audit $"report {id} served"
                    with ex ->
                        eprintfn "audit failed: %s" ex.Message
                }
            Async.Start(audit, ct)
            return report
        }
    Async.StartAsTask(work, cancellationToken = ct)

Exceptions

  • An exception inside task { } faults the returned task. Code before task { } throws at
    the call. Keep validation inside the builder so callers see one failure path.
  • let! and GetAwaiter().GetResult() give the original exception. .Result, .Wait(), and
    Async.AwaitTask give AggregateException. Inside async, a try ... with around
    Async.AwaitTask also sees AggregateException, so with :? MyException and F# exception
    patterns do not match. Unwrap one level at the boundary: match
    :? AggregateException as a when a.InnerExceptions.Count = 1 and raise a.InnerExceptions.[0]. Task.WhenAll faults with every inner
    exception, and let! rethrows only the first.
  • Cancellation surfaces as OperationCanceledException or TaskCanceledException. Do not
    catch it with a general with ex -> that logs and continues.

ValueTask

A ValueTask<'T> can be consumed once. A pooled source, such as a socket, recycles its
storage when you read the result. A second read throws InvalidOperationException. A Task
source does not throw, so the defect appears only when the source is pooled.

  • Do not let! the same ValueTask twice. Do not read .Result after let!.
  • Do not pass vt.AsTask() to Task.WhenAny and then read vt.Result. Keep the Task:
    let t = vt.AsTask(), then await t as often as needed.
  • Do not store a ValueTask in a field or a list for later. Convert it with AsTask() first.
let read = source.ReadAsync().AsTask()
let! winner = Task.WhenAny(read, Task.Delay timeoutMs)
if obj.ReferenceEquals(winner, read) then
    let! frame = read
    return Some frame
else
    return None

State machine diagnostics

  • FS3511: the compiler cannot compile a task state machine statically and uses a slower
    dynamic one. A let rec inside the builder is one cause. Move the let rec outside the
    builder. Other causes are non-inlined lambdas that hold resumable code and some
    generic-constraint cases. Treat FS3511 on a hot path as a defect.
  • FS3501 and the related resumable-code errors come from a custom builder. Builder methods
    that take or return resumable code must be inline. Use an existing builder from IcedTasks
    or FsToolkit before you write one.

Verify

  1. Test each function that takes a CancellationToken. Cancel during the work. Check that the work stops, not only that the returned task completes.
  2. For each fire-and-forget call, check that the side effect happens.
  3. For a ValueTask API, test with a source that throws on a second read, as in
    scripts/Proofs.fsx.
  4. Build in Release and treat FS3511 on changed code as a failure.

To check the facts in this skill, run the bundled proof:

pwsh ./scripts/run.ps1

The runner runs scripts/Proofs.fsx and builds
scripts/StateMachine in Release. It fails when a fact differs or when
FS3511 is not reported only for the let rec case. Each PASS line prints one fact and its
observed value. The IcedTasks version is pinned in the script.

This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

Browse all →
fsharp-performance-typesChoose F# collections and types for run time and allocation, and prove the result with a measurement. Use when F# code is slow or allocates too much, when a reviewer asks for fewer passes or allocations, or when you write a hot loop over list, array, seq, Map, Set, Dictionary, option, tuple, or sprintf.0 installsfsharp-nullness-interopHandle F# nullness checking (Nullable enable, FS3261, FS3262 in F# 9 and later) at .NET interop boundaries, and fix FS0041 "A unique overload could not be determined" from new BCL overloads such as TimeSpan.FromSeconds(int64). Covers BCL members that return `| null`, correct null handling with match and Option.ofObj, null leaks that the compiler does not report, and when suppression is acceptable. Use when an F# build reports FS3261, FS3262, or FS0041, when the user turns on nullness checks or TreatWarningsAsErrors, or when F# code calls .NET APIs that can return null.0 installsoptimize-fsharp-typecheck-graphOptimize an F# project's graph-based type-checking critical path with measured compiler evidence. Use when an F# build spends substantial time in type checking, a `.graph.md` file shows excessive file dependencies, shared namespaces or auto-open modules serialize checking, signature files may unblock parallel work, or a compile-performance refactor needs source- and binary-compatibility validation.0 installsfsharp-signature-filesAdd F# signature files (.fsi) that expose only the API that callers use, and hide type representations so callers must use constructor functions. Covers generating a starting point with --allsigs or --sig, removing helpers from the .fsi, abstract types, attribute and interface mismatches (FS3888, FS0050, FS1200), signature errors (FS0034, FS0193, FS0238), XML docs, InternalsVisibleTo for tests, and a public-surface check of the built assembly. Use when the user asks for signature files, a smaller public API, encapsulation of an F# library, or hidden constructors.0 installsfsharp-native-aotMake F# code work under .NET Native AOT (PublishAot) and find the failures that publish warnings do not show. Covers which printf, sprintf, failwithf, and interpolated-string forms work, silent data loss from %A and ToString on unions and tuples, logging, System.Text.Json for F# records, option, list, and unions, configuration binding, warnings-as-errors, and JIT-versus-native verification. Use when an F# project sets PublishAot or PublishTrimmed, when the user asks about F# AOT or trimming, when F# output or logs differ in a native build, or when F# JSON fails with "Reflection-based serialization has been disabled".0 installsfsharp-failure-pathsMake failures in F# code explicit instead of crashing or hiding them. Use when writing or reviewing F# that calls partial functions (List.head, Seq.find, Map.find, .Value), uses failwith, falls back with defaultArg or Option.defaultValue, catches exceptions, or combines several validations into one Result.0 installs

More from F# Skills

View source →
fsharp-env-capabilitiesPass dependencies in F# as one generic env value whose capabilities are small IProvideX interfaces, so the compiler infers each function's dependency set and tests build only what a function needs. Also binds IConfiguration settings to F# types, validates them with Result at startup, and exposes the validated type as a capability instead of IOptions<T>. Use when an F# function list of dependency parameters grows, when wiring IServiceProvider or ASP.NET Core DI into F# functions, when binding or validating appsettings.json or IOptions settings in F#, when a test must substitute one dependency, or when the user says env, capability, IProvide, or environment pattern.0 installsfsharp-iwsam-errorsDesign F# error types as IWSAM leaves (interfaces with static abstract members) so each function declares only its own errors and the caller picks one edge type. Use when adding or composing Result error types across F# functions, when a nested error DU needs Result.mapError at every call, when a new error case must reach every handler, or when the user says IWSAM, error tree, or edge type.0 installsfsharp-library-api-designDesign and change the public API of an F# library without breaking its consumers. Covers F#-specific breaking changes (new union cases, new record fields, curried and tupled forms, generic and inline functions, RequireQualifiedAccess, renamed modules), binary breaks that a clean build does not show (a new optional parameter, a wider parameter type, cross-assembly inlining of a small function body into Release consumers, --nooptimizationdata), safe extension patterns (overloads, new functions), a C#-friendly surface, SemVer for each change type, the lowest FSharp.Core version, and compatibility checks with package validation and old consumers. Use when the user adds to or changes a published F# library, asks whether a change is breaking, picks a version number, or exposes F# code to C#.0 installsfsharp-serializationSerialize F# records, unions, options, and maps to JSON that matches a wire contract, and keep old JSON readable. Use when writing or reviewing F# code that calls System.Text.Json, configures FSharp.SystemTextJson (JsonFSharpConverter, JsonFSharpOptions), writes Thoth.Json encoders or decoders, adds a DTO layer, reads JSON from another service, or adds or renames a union case or record field that is stored or sent as JSON.0 installsfsharp-verify-apiCheck the real signature of a .NET or F# API before F# code uses it, so the build does not loop on FS0039, FS0001, FS0074, or FS0078. Use when writing F# against a NuGet package, a package version that changed its API, an unfamiliar type, or an .fsx script with0 installsfsharp-binary-compatibilityChange a published F# library so that apps compiled against the old version still run against the new DLL with no rebuild. Covers new parameters on let-bound functions (no overloads), optional member parameters, inferred type changes, union case order and new cases, record fields, inline and [<Literal>] values, cross-assembly inlining (--nooptimizationdata), renames with CompiledName, curried and tupled parameters, abstract interface members, the FSharp.Core dependency, and automated checks with package validation, apicompat, and an F# signature diff. Use when the user changes the public API of an F# library or NuGet package in a minor or patch release, asks for a non-breaking change, or asks whether an F# change is binary compatible.0 installs

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.635 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.535 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.346 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.246 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.173 installsusing-superpowersUse when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions145 installs

Frequently asked questions about fsharp-async-composition

What does the fsharp-async-composition skill do?

Compose F# Task, Async, and ValueTask code with the correct semantics and builder (task, async, valueTask, cancellableTask, taskResult). Covers hot and cold start, boundary conversion, cancellation flow, exception wrapping, and ValueTask values read twice. Also covers FS0193, FS3501, and FS3511. Use when F# code mixes Task and Async, or returns or consumes ValueTask. Also use when code passes a CancellationToken, starts fire-and-forget work, or changes its async type. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the fsharp-async-composition skill?

Run `npx @skills-hub-ai/cli install fsharp-skills-fsharp-async-composition` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/fsharp-skills-fsharp-async-composition/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does fsharp-async-composition work with?

fsharp-async-composition runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the fsharp-async-composition skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use fsharp-async-composition after installing it?

In Claude Code, type `/fsharp-skills-fsharp-async-composition` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the fsharp-async-composition skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.