Skip to content

Types and schemas

Types describe values independently of their byte representation. A schema projection produces a Rastok type; it does not install a wire codec or a Driver. The types chapter introduces the notation.

Use the names in the first column in .rkg declarations. Their widths are fixed, not chosen by the machine. A computed value can enter another numeric type without a written conversion only when every value of its type fits.

An annotation is the type you read back: val seven: decimal = 7u binds a decimal, while val seven = 7u binds a uint.

Source typeRepresentation and boundsComputation in this alpha
sbyte, short, int, longSigned 8-, 16-, 32- and 64-bit integersArithmetic, ordering and equality. Division truncates toward zero; carrier overflow and division by zero fault. A result must fit its destination.
byte, ushort, uint, ulongUnsigned 8-, 16-, 32- and 64-bit integersArithmetic, ordering and equality. Carrier overflow, underflow and division by zero fault.
half, float, doubleBinary16, binary32 and binary64Arithmetic at the result width, ordering and equality. Results can include infinities and NaN; ordering a NaN faults.
decimalExact integer or decimal, not binary floating pointCarrying, schema projection, equality and explicit narrowing; no arithmetic or ordering
decimal(p,s)Exact decimal128 coefficient and scale; precision 1..38, scale -38..38Carrying, schema projection and equality; exact conversion from integers or decimal; no arithmetic or ordering, and narrowing never rounds

An unsigned literal chooses the first width that holds it: 7u is uint, 4294967296u is ulong. There is no separate ulong suffix. Write int, not int32, and half, not float16. Without context, a floating literal uses double. Where a float is expected, 0.1 and 4.099999904632568359375 both fit: the first keeps its displayed value, the second is exactly representable. A literal may also fit double by either rule and then fit float exactly: 0.10000000149011612 fits and displays 0.1. Neither 0.1000000015 nor 0.123456789 fits.

Values that meetType used
int and longlong
int and double, or float and doubledouble
An integer and decimaldecimal
An integer and decimal(p,s), or two fixed decimalsThe smallest fixed decimal that holds both, otherwise decimal
int and uintlong
long and double, int and ulong, or float and decimalNo common type; convert explicitly with as?

A float widened to double or carried as a variant keeps the value its shortest rendering denotes. Lists, map values and struct fields can widen when their contents can.

The % result has the dividend’s sign, including a negative zero. Floating remainder uses a quotient truncated toward zero. A zero divisor, infinite dividend or NaN operand yields NaN; a finite dividend modulo an infinite divisor is unchanged. Two declared decimals compare by value: 19.90 at scale two equals 19.900 at scale three. Each keeps its own scale for display. Two decimal values also compare by value: seven equals decimal("7.00"). Neither comparison rounds. decimal cannot be a map or instance key. See numeric expressions for conversion examples and fault behavior.

TypeParameters and aliasesValue rule
boolNo parametertrue or false
nullNo parameterThe null value
stringNo parameterUnicode text
array<byte>Variable lengthCompact byte sequence; size(b) counts bytes and b[?i] returns a byte?
array<byte,N>Fixed length in sourceExactly N bytes; 1 <= N <= 2147483647
uuidNo parameterExactly 16 network-order bytes
string(max)Maximum length in Unicode scalar values"été" fits string(3)?, and ["été"] fits array<string(3)>. When the input may be longer, use as? string(3) and handle null. JSON Schema preserves maxLength; Avro and Arrow return LossyProjection at this field.

Source declarations in this version accept only the bare names date, time, timestamp, timestamp_ntz and duration. They use the defaults below. Parameterized forms and calendar intervals belong to the logical model and transported schemas; they are not source type declarations. interval is not a built-in source type, either bare or parameterized.

For logical time, timestamp, timestamp_ntz and duration, the unit is second, millisecond, microsecond or nanosecond. These parameterized temporal declarations are refused with E-PARSE-DEFERRED, naming the form. This does not affect value constructors such as duration("2s") or timestamp("2026-10-30T12:00:00Z").

Logical typeSource default or logical parametersDistinction preserved
date(unit)day or millisecond; bare date means dayDate, carried as whole days
time(unit)Bare time means nanosecondsTime of day, without a date
timestamp(unit, "zone")Bare timestamp means nanoseconds in UTCInstant with a declared zone; UTC, Etc/UTC and +00:00 normalize to UTC
timestamp_ntz(unit)Nanoseconds by defaultDate and time without a zone; not UTC by omission
duration(unit)Nanoseconds by defaultSigned elapsed quantity, carried in i64 nanoseconds
interval(year_month)MonthsCalendar interval
interval(day_time)Days and timeCalendar interval with millisecond precision
interval(month_day_nano)Signed months, days and nanosecondsArrow interval constraints
interval(month_day_millis_unsigned)Unsigned 32-bit months, days and millisecondsAvro duration constraints, distinct from the Arrow interval

Timestamp carriers contain signed i64 seconds and a nonnegative nanosecond fraction. The unit limits precision, not the seconds range. Arithmetic outside the carrier refuses. Logical execution time and civil timestamps are separate: now() observes the recorded origin plus the transaction’s logical instant.

as? Record checks the fields of either a struct or a JSON object against the declared record. For example, an unsigned seven can fill a long field; an unsigned value outside the long range makes the whole cast return null.

FormMeaningConstraints
struct { name: string, count: int }Named fieldsClosed, unique fields; declaration order is not type identity
array<T>Ordered homogeneous sequenceVariable length
array<T,N>Fixed sequence in the logical model onlyExactly N elements, including N = 0; source declarations refuse this form with E-PARSE-DEFERRED
map<K,V>Homogeneous keyed collectionCanonical, non-null scalar or enum keys
enum { Ready, Done }Named unit casesWrite Ready or Done where this enum is expected, including a typed list element or opposite an enum operand of == or !=; a conflicting visible binding refuses
T?T or nullAbsence and null are distinct at a boundary
A | BStructural unionBranches must be pairwise disjoint; exactly one branch matches
union { Ok { value: string }, Refused }Tagged unionNamed cases with closed payloads; the case remains part of the value
variantSelf-describing value treeTest its type with is. To read a schemaless JSON object as a declared struct, use as? T and handle null.

An optional enum E? resolves bare symbols wherever enum E does, including collection values and Lab assertions; a union with several non-null branches does not select an enum for a bare symbol.

In the logical model, map keys admit booleans, fixed-width integers, strings, byte arrays, fixed-scale decimals, dates, times, timestamps, durations, UUIDs and enum symbols. Floats, decimal, null, intervals, dynamic values and composite keys refuse. Instance keys additionally admit closed structs of valid key leaves.

Source map literals accept only string keys: { "id": "a" } is a map, while { 1: "a" } is refused. For map<string(3), long>, {"été": 1} fits and {"abcd": 1} is refused at check. A non-string key type can still be declared, for example map<int, string>, but only its empty literal {:} can be written in this version. Fixed-length arrays can be written only for byte. The bytes connector codec still names a wire format. Neither a byte array with a declared schema nor bytes carried in a variant have a JSON wire form.

Named type declarations are structural aliases. Recursive aliases refuse. Type trees are bounded to 128 nesting levels, 4096 nodes and 256 members per aggregate. type Name = @struct { ... } declares a flat, annotation-capable struct; annotation use and interpretation are described in Privacy, secrets and measurements.

The standard library lists the named types available without imports, including FileExit and ProcessExit. They use the same definitions as the Connector ports, independently of the physical Drivers included in the binary. Write output failed: FileExit without copying its declaration; the library reference explains name collisions and the module and import design still to be discussed.

SpellingResultNotes
42, 42u, 1.5, true, null, "Ada"Intrinsic scalarOrdinary expression literals retain their checked type
decimal("12.30")decimal carrying an exact decimalA declared decimal target checks precision and rescales exactly
duration("2h30m")durationSigned duration; units include h, m, s, ms, us, ns
{ room = "kitchen", celsius = 21 }Declared structBraced field assignments, name = value, checked against the struct type expected where the literal appears
[], {:}Empty array, empty mapUse the expected type; without one, array<variant> and map<string,variant>; {} is an empty struct, not a map
timestamp("2026-10-30T12:00:00Z")timestampParsed civil instant
json! { "count": 42 }variantAlso accepts scalar JSON. Duplicate keys and numbers without a lossless long, ulong or double representation refuse.
string! { message }stringVerbatim reader
base64! { SGk= }array<byte>Standard base64, padding required; ASCII whitespace ignored
asset("fixtures/sample.pdf")array<byte>Bytes read at build time and embedded in the plan

Tagged frontends occupy a complete value position. Bind their result before using it inside a larger expression. See Expressions and dispatch.

Without an expected type, val members = [] infers array<variant> and val counts = {:} infers map<string,variant>. The same rule applies to { items = [] }. A destination requiring more precise elements refuses such a binding with E-PORT-TYPE; annotate the declaration instead: val members: array<string> = [] or var counts: map<string, int> = {:}. With elements, val members = ["alice"] infers array<string>; mixed elements such as [1, "a"] infer array<variant>. The type belongs on the declaration: there is no array<string> [] value prefix.

A typed list checks each element against its declared element type, as a typed map does for its values. With data: string, write val names: array<string?> = [null, data]. Without that expected type, [null, "a"] still infers array<variant>.

An optional map keeps the same value context: for map<string,int?>?, { "a": null, "b": 1 } constructs the optional values before the optional map. Likewise, an enum symbol resolves inside an optional collection: with Status = enum { Pending, Done }, write [Pending] for array<Status>? or { "x": Done } for map<string,Status>?. A union with several non-null branches does not choose a collection branch for a bare symbol.

A JSON-encoding Connector input refuses a known producer type containing array<byte>, duration, timestamp, date, time, timestamp_ntz, interval, uuid, a map with non-string keys, or a tagged union, at any depth. E-TYPE-INVALID names the input and the first offending field. Convert the value explicitly before sending it. Enum symbols, exact decimals, finite floats, optional fields and maps with string keys have JSON forms.

A variant producer passes this static check; a JSON value can be forwarded directly to another JSON Connector. Its value remains subject to the runtime encoder. A variant field does not hide a known non-JSON field elsewhere in the producer type. See the individual Contracts for their runtime refusals. Response decoding is a separate constraint: an encodable request type is not necessarily an admitted JSON response type.

The schema projection adapters report a path and a named loss reason. Reverse projection succeeds only when projecting the result back preserves the logical type. Source field order, physical union indexes and layout do not become type identity.

RefusalMeaning
UnsupportedSourceConstruct outside the admitted source subset
UnsupportedTargetNo exact representation in the selected target
InvalidSchemaInvalid schema or invalid parameters
RecursiveSchemaReference cycle
LossyProjectionConversion would discard a constraint or distinction
AmbiguousUnionOverlapping branches
InvalidMapKeyKey outside the canonical-key domain
BudgetExceededResolved type exceeds a type-tree bound

A declared decimal, decimal(p,s), long or ulong field also accepts a JSON string that spells an exact number in range. For example, the string "9007199254740993" enters a long unchanged; "01" is not a valid JSON number. Output uses an unquoted number.

Source or directionProjection or refusal
null, boolean, string, number, integernull, bool, string, double, long
Integer with inclusive bounds exactly matching a machine widthCorresponding signed or unsigned integer
Integer range 0..10LossyProjection, rather than widening to a machine integer
String enum; homogeneous array; equal minItems and maxItemsEnum; variable array; fixed array
Required named properties and additionalProperties: falseClosed struct
Schema-valued additional properties without named fieldsmap<string,V>
Null plus one type; disjoint oneOfOptional; structural union
Optional property without a fill policy; required key on a mapLossyProjection
Boolean schema, pattern, conditional constraints, tuple prefixesUnsupportedSource
Cyclic local reference; overlapping oneOfRecursiveSchema; AmbiguousUnion
Invalid definition or empty type arrayInvalidSchema
Reverse bytes, decimal scale, time units or tagged discriminants without an extension profileUnsupportedTarget
Source or directionProjection or refusal
Null, boolean, int, long, float, double, bytes, stringMatching types; Avro bytes gives array<byte> and integers retain 32/64-bit widths
Fixed, record, array, string-keyed map, enumarray<byte,N>, closed struct, array, string-keyed map, enum
Decimal logical typeDecimal128, precision up to 38, 0 <= scale <= precision; fixed storage must fit
Date, time, timestamp and local-timestamp logical typesMatching date/time constructors, including zone-free timestamps
Duration; UUIDinterval(month_day_millis_unsigned); uuid
Disjoint union branchesStructural union with an explicit branch-index mapping
Same-shape named record branchesTagged union using resolved names
Recursive recordRecursiveSchema
Precision 39 or unknown logical typeUnsupportedSource
Insufficient fixed decimal storage, forward undefined name or duplicate underlying union branchInvalidSchema
Reverse type without an exact Avro formUnsupportedTarget or LossyProjection
Source or directionProjection or refusal
Integers, floats, decimal128Width, sign, precision and signed scale preserved
Binary, large binary, binary view; UTF-8 variantsarray<byte>; string
Fixed binary; list variants; fixed listarray<byte,N>; variable array; fixed array
Date, time, timestamp, duration, intervalUnit and zone preserved
Struct, nullable field, mapClosed struct, optional field, canonical-key map
Dictionary or run-end encodingDecoded logical value type
Dense or sparse unionTagged union with explicit child-name/type-code mapping
Extension type, decimal32/64/256 or out-of-range scaleUnsupportedSource
Nullable or unsupported map keyInvalidMapKey
Duplicate union type codes or child namesInvalidSchema
Reverse tagged union with 129 casesUnsupportedTarget: the flat target union cannot address that many children

rastok --resolve-open-api <project-dir> [--check] discovers static HTTP endpoints and generates openapi.generated.rkg. It leaves authored sources untouched. --check reports a missing or stale generated file without writing.

SourceProjection or refusal
Local component referenceExpanded alias; cycles give RecursiveSchema
3.0 nullable: true; 3.1 type array with nullT?
Integer format int32 or int64int or long, respectively; unbounded integer gives LossyProjection
Number, number format float/doubledecimal, float or double, respectively
String, uuid, date, date-time, binary/byte, media-type formatsstring, uuid, date, timestamp, array<byte>, string, respectively
Fully required closed object; pure additional-property mapClosed struct; map<string,V>
Disjoint oneOfStructural union
Optional fields, open/mixed object or required map keysLossyProjection
Unknown format, discriminator, readOnly or writeOnlyUnsupportedSource
Dynamic endpoint, no matching document or ambiguous documentResolver refusal; no guessed endpoint
Component name that is a standard type nameUnrepresentableName; no conflicting declaration is written

The HttpClient json_profile = projected setting is a separate boundary policy: it can skip extra fields and fill omitted nullable fields with null. It still rejects a wrong type or missing required field. It does not widen the OpenAPI schema projection above.

ItemSpecification
Registered extension profiles for projections that need additional schema vocabularydocs/spec/schema-projections.md §§1–4
Decoder availability resolved through an attested registrydocs/spec/envelope.md §5.1

Sources: docs/spec/types.md, docs/spec/schema-projections.md; executable projection evidence in crates/rastok/tests/schema_projections.rs and the OpenAPI projection/resolver tests. Runtime wire support remains specific to each Contract.

Diagram