Schema to Arbitrary
Arbitrary derives random value generators and shrinkers directly from schemas for property-based testing. The module and its replay token format are unstable in Effect 4.1.1. Plain builders follow the call rules.
Generating samples
const Parcel = Schema.Struct({
label: Schema.NonEmptyString,
count: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 24 }))
})
effect function sampleParcels() {
const generator = try sync(() => Arbitrary.schema(Parcel))
return try Arbitrary.sampleEffect(generator, { count: 12, seed: "parcel-samples" })
}
// Run in an effect function:
// const values = try sampleParcels()
// try Console.log(values.length, values.every(Schema.is(Parcel)))12 trueArbitrary.schema builds a generator synchronously (failing as a defect if derivation is unsupported). Arbitrary.sampleEffect accepts count, size (a per-component complexity budget), maxDiscards, and a deterministic seed.
Filters and constructive constraints
const EvenCapacity = Schema.Number.check(Schema.makeFilter(
(value) => Number.isInteger(value) && value >= 2 && value <= 40 && value % 2 === 0,
{
expected: "an even capacity from 2 to 40",
arbitraryConstraint: {
order: Order.Number,
minimum: 2,
maximum: 40,
number: "integer"
}
}
))
// Run in an effect function:
// const generator = try sync(() => Arbitrary.schema(EvenCapacity))
// const values = try Arbitrary.sampleEffect(generator, { count: 12, seed: 17 })
// try Console.log(values.length, values.every(Schema.is(EvenCapacity)))12 trueBuilt-in bounds, lengths, patterns, and uniqueness checks drive construction automatically. For custom predicates, add arbitraryConstraint to narrow generation while still enforcing the predicate on every generated and shrunk candidate.
Decoded vs. encoded generation
effect function sampleRepresentations() {
const decoded = try sync(() => Arbitrary.schema(Schema.FiniteFromString))
const encoded = try sync(() => Arbitrary.schema(Schema.toEncoded(Schema.FiniteFromString)))
const numbers = try Arbitrary.sampleEffect(decoded, { count: 4, seed: 17 })
const strings = try Arbitrary.sampleEffect(encoded, { count: 4, seed: 17 })
return { numbers, strings }
}
// Run in an effect function:
// const values = try sampleRepresentations()
// try Console.log(values.numbers.length, values.numbers.every(Number.isFinite))
// try Console.log(values.strings.length, values.strings.every((value) => typeof value === "string"))
// try Console.log(values.strings.some((value) => Schema.decodeUnknownResult(Schema.FiniteFromString)(value).isFailure()))4 true
4 true
trueArbitrary.schema targets the decoded type (number for FiniteFromString). Project with Schema.toEncoded to sample raw encoded-side values, or encode generated decoded values to produce guaranteed-valid wire data. Opaque predicates without constructive constraints burn through maxDiscards, failing sampling with SampleError and returning Exhausted from property checks.
Checking properties
effect function checkCountRoundTrip() {
const Count = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))
const generator = Arbitrary.schema(Count)
const result = try Arbitrary.checkEffect(generator, effect (count): boolean!Schema.SchemaError!never => {
const wire = try Schema.encodeEffect(Schema.FiniteFromString)(count)
return (try Schema.decodeEffect(Schema.FiniteFromString)(wire)) === count
}, { runs: 200, seed: "count-round-trip" })
return result
}
// Run in an effect function: try Console.log((try checkCountRoundTrip())._tag)PassedArbitrary.checkEffect runs a pure or effectful boolean property and returns Passed, Falsified, Exhausted, or ReplayMismatch:
- Returning
falseor failing with a typed error triggers shrinking; defects and interruption fail the outer Effect. FalsifiedcarriesshrunkInputand areplaytoken; pass{ replay: result.replay }to reproduce the exact failing case.Arbitrary.formatCheckFailure(result)formats a diagnostic string for non-Passedoutcomes.
Composing generators and shrinking
effect function sampleDispatchPlans() {
const counts = try sync(() => Arbitrary.schema(Schema.Int.check(
Schema.isBetween({ minimum: 0, maximum: 32 })
), {
shrink: (value) => value === 0 ? [] : [Math.floor(value / 2)]
}))
const plans = Arbitrary.all({
count: counts,
label: Arbitrary.Constant("test-dispatch")
})
return try Arbitrary.sampleEffect(plans, { count: 6, seed: 91 })
}
// Run in an effect function:
// const values = try sampleDispatchPlans()
// try Console.log(values.length, values.every((plan) => plan.label === "test-dispatch" && Number.isInteger(plan.count) && plan.count >= 0 && plan.count <= 32))6 trueCompose generators with map, flatMap, all, filter, filterMap, and Constant. A custom shrink callback replaces shrinking only (not root generation) and must be synchronous, deterministic, terminating, and pure. Treat generated values as immutable.
Custom declarations
class ShelfRef {
constructor(readonly code: `shelf_${string}`) {}
}
const ShelfRefSchema = Schema.instanceOf(ShelfRef, {
toCodecArbitrary: () => Schema.link<ShelfRef>()(
Schema.TemplateLiteral(["shelf_", Schema.String]),
SchemaTransformation.transform({
decode: (code) => new ShelfRef(code),
encode: (ref) => ref.code
})
)
})
effect function sampleShelves() {
const generator = try sync(() => Arbitrary.schema(ShelfRefSchema))
return try Arbitrary.sampleEffect(generator, { count: 5, seed: 23 })
}
// Run in an effect function:
// const values = try sampleShelves()
// try Console.log(values.length, values.every((shelf) => shelf instanceof ShelfRef && shelf.code.startsWith("shelf_")))5 trueSupply toCodecArbitrary on opaque declarations to link them to a generatable schema.
Diagnosing derivation failures
effect function reportImpossibleGenerator() {
const outcome = try exit(sync(() => Arbitrary.schema(Schema.Never)))
if (outcome is Exit.Failure) {
try Console.log("Arbitrary derivation failed for the empty domain")
}
}
// Run in an effect function: try reportImpossibleGenerator()Arbitrary derivation failed for the empty domainDerivation fails immediately on Schema.Never, contradictory bounds, unhooked declarations, or ungrounded recursion. Capture derivation defects with exit when testing schemas, and record the seed or replay token with failing property tests.
The matching Effect page: effect.website/docs/v4/schema/arbitrary