Implemented language — SDK 0.19.0 Developer Preview

This specification describes the 0.15.0 language implementation, including nominal enums and bounded HTTP routing/response headers. Artifact and platform validation are recorded separately in the versioned release report.

The full language direction is in docs/LANGUAGE-DESIGN.md in the project source. This file describes what this compiler actually accepts. All features remain Developer Preview.

Layout and scalar types

Two spaces per indentation level, no tabs. A colon opens a block. End statements with newlines. Legacy brace/semicolon files still compile; do not mix block styles within a file. Function inputs have explicit types. An omitted output type means Void. Scalar types are Int (signed checked 64-bit), Bool and String (immutable UTF-8; len counts Unicode scalar values). Lowercase scalar names remain compatible. Integer separators such as 10_000 are supported. There is no float or language-level null. Enums declare a fixed set of named values. Immutable lists use Int[], Bool[], String[], or a declared record or enum type such as User[] or OrderState[]. Optional values use T?, some(value) and none.

fn greet(name: String) -> String:
  return "Hello, " + name

fn main():
  name = "Erwin"
  mut count = 0
  while count < 3:
    print(name |> greet)
    count = count + 1

First assignment declares an immutable local in the current block. mut name = value permits reassignment. Parameters are immutable. Legacy let keeps its old mutable semantics for migration. Binding types cannot change. if, else, while, break, explicit return and recursion are implemented. All value-returning functions must return on every path. Top-level declarations are functions, record types, enum types and routes; arbitrary top-level statements are not supported.

Local source imports

Native SDK check/emit/build/run and project tests load imports before compiling:

import "lib/user.one"
import "lib/messages.one"

fn main():
  print(greet(User(name: "Ada", bio: none).name))

See examples/modules for a complete three-file JSON API. Imports must be unindented, one per line, before declarations (blank lines and // comments are allowed). Paths use ASCII letters/digits, underscore, dot, dash and slash; they must end in .one. Paths resolve relative to the importing file. Absolute paths, parent traversal and symlinks escaping the entry file directory are rejected. Only regular UTF-8 files are loaded. The graph is limited to 64 distinct files including the entry, 16 import edges deep, and 1 MiB total source bytes. Canonical paths are loaded once in deterministic depth-first order; cycles are errors. These checks are project hygiene, not a sandbox against concurrent filesystem changes.

All imported functions, records, enums and routes share one program namespace. Duplicate names and duplicate routes are errors. There are no aliases, private exports, packages, network imports, per-module state or runtime initialization. Declaration order does not limit calls, record references or enum references. Each file normalizes its own block style; separate brace and indentation files can coexist. Diagnostics identify the originating file and line. Output paths cannot replace an entry or imported source. The import name is reserved in this preview.

The browser Playground remains single-file: imports report that the native SDK file loader is required. It does not read local files. Namespaced modules and richer collection types remain future work.

Nominal enums — enum implementation

An enum declares a closed set of named values. Use qualified case syntax such as OrderState.Paid. The enum name is part of the type: two enums that both declare Active still have different types. Case names are case-sensitive. There is no implicit conversion from String or Int, and enum values cannot be ordered or used in arithmetic.

enum OrderState:
  Pending
  Paid
  Cancelled

type Order:
  state: OrderState
  previous: OrderState?
  allowed: OrderState[]

fn ready(state: OrderState) -> Bool:
  return state == OrderState.Paid

fn main():
  order = Order(state: OrderState.Paid, previous: none, allowed: [OrderState.Pending, OrderState.Paid])
  print(order.state)
  print(ready(order.state))
  print(order.previous or OrderState.Pending)
  print(list_get(order.allowed, 1) or OrderState.Cancelled)

Enum values support same-type equality, function parameters and returns, record fields, homogeneous lists and Optional values. EnumName! and EnumName?! follow the existing fallible and absence-recovery rules. EnumName[]? and EnumName[]! remain unsupported, like other Optional/fallible list types. print and str produce the exact declared case name, without a type prefix. Comparing values from different enum types is a type error, even if their case names have the same spelling.

A program may declare at most 256 enum types, separately from the record limit. Each enum declares 1 to 64 cases. Enum and case names are ASCII identifiers of at most 64 bytes; reserved names and the compiler prefix are rejected. Enum declarations can be referenced before their source position. Enum type names cannot collide with record or function declarations. A parameter or local binding may shadow an enum name in expressions: Status.Active denotes an enum case only when Status is not bound in that scope; otherwise ordinary field access must type-check. Type positions and parse_json(text, Status) still resolve the declared enum type. Cases may share a name across different enum types. Legacy brace syntax uses semicolons: enum OrderState { Pending; Paid; Cancelled; }.

Native JSON represents an enum as an exact case-name string, for example "Paid". parse_json(text, OrderState) and req.json(OrderState) return OrderState!. Unknown names, different case, numbers, null, arrays and tagged objects are decoding errors. A record's Optional enum field accepts an omitted or null value as none; a required enum field does not. Enum list fields accept only arrays of declared case-name strings, with the existing 1,024-element and cumulative JSON-list-storage limits. Decoding errors do not echo the supplied enum value. Typed enum values constrain data; they do not authenticate users or enforce authorization.

enum OrderState:
  Pending
  Paid

fn main():
  state = parse_json("\"Paid\"", OrderState) or OrderState.Pending
  print(state)
  print(json_encode(state) or "Encoding failed")

The native example prints Paid, then the JSON string "Paid". Pure enum operations also run in the browser interpreter; JSON and HTTP execution remain native-only. This enum milestone does not include payloads, explicit numeric discriminants, match expressions, reflection or exhaustive-branch checking. Use ordinary equality and if/else branches, and return a value on every path when required.

Immutable records

type Address:
  city: String

type User:
  name: String
  address: Address

fn city(user: User) -> String:
  return user.address.city

fn main():
  user = User(name: "Erwin", address: Address(city: "Bangkok"))
  print(city(user))

Fields have explicit Int, Bool, String, record or enum types, optionally suffixed with ?, or list types (Int[], Bool[], String[], or declared record/enum types such as User[] and OrderState[]). Lists cannot be suffixed with ?. Constructors require named arguments for every field exactly once; positional or mixed arguments are rejected. Expressions are evaluated once in source order, even when named arguments use a different order from the declaration. Field reads use value.field. Record values are copied by value; their immutable strings refer to the owning arena. Fields cannot be assigned to. A mut record binding permits replacement of the whole value, not field mutation.

Forward type references are allowed, but recursive record shapes and empty records are rejected. A program may declare at most 256 record types; each has at most 64 fields. Expanded shapes are limited to depth 16, 256 scalar leaves and a 64 KiB native inline-layout budget. Fallible and Request/Response fields are not supported. Optional record fields still count toward shape limits; ? does not permit recursive records. Records may be function parameters or results, including User!. Record equality compares field values. print and str accept scalar and enum values; use json_encode or field access for records.

Immutable lists

Int[], Bool[], String[], record lists such as User[] and enum lists such as OrderState[] hold an ordered, homogeneous sequence, with at most 1,024 elements per list. Record and enum elements must all have the same declared type. Their conservative native inline layout is limited to 256 bytes per element; a larger record can still be used outside a list. List literals must fit on one source line in this preview; bracket continuation is not implemented. A nonempty literal infers its element type. An empty literal needs an expected list type from a typed binding, parameter, return or record field.

type Batch:
  names: String[]
  quantities: Int[]

fn total(values: Int[]) -> Int:
  mut index = 0
  mut sum = 0
  while index < len(values):
    sum = sum + (list_get(values, index) or 0)
    index = index + 1
  return sum

fn main():
  empty: Int[] = []
  batch = Batch(names: ["Ada", "Erwin"], quantities: [2, 3])
  print(len(empty))
  print(total(batch.quantities))
  print(list_get(batch.names, 1) or "Unknown")

len(list) returns its element count. list_get(list, index) returns the element as an Optional scalar, record or enum; negative and out-of-range indices return none. Handle absence explicitly with the existing Optional operations. There is no bracket indexing or element assignment. Values and list contents remain immutable; a mut list binding permits replacement of the whole list, with the same element type. List values can be function parameters, ordinary function results and record fields. List equality compares ordered contents. Record list equality compares the fields of each corresponding element, with the same record type required on both sides. A record element may itself contain Optional fields or lists, provided the declared record graph is acyclic. Record graph cycle detection and the depth-16/256-leaf shape limits follow record-list edges. A list field does not permit recursive records, even when every value in a program would be an empty list.

Lists can be encoded as JSON arrays, including inside records. Record elements encode as JSON objects; their fields retain the existing strict record decoding rules (including duplicate/unknown fields and Optional handling). Record JSON decoding accepts correctly typed arrays, rejects nonarrays or incorrectly typed elements, and rejects arrays exceeding 1,024 elements. The existing 1 MiB JSON input/output limits still apply. Decoding also limits cumulative list storage to 8 MiB per JSON document; exceeding the budget returns a decoding error. This budget does not bound total process memory or JSON/string intermediates. Top-level parse_json and req.json require a declared record or enum schema; use a record field for incoming arrays. Enum elements encode as exact case-name JSON strings and reject undeclared or differently cased names during decoding. List length does not replace application-specific checks such as matching two fields' lengths.

This preview does not support Optional elements, directly nested list types (such as Int[][]), Optional/fallible list types (Int[]? or Int[]!), mutation, append, slicing or generic collection functions. print and str do not accept a whole list; print selected scalar/enum elements or use native json_encode. The browser supports pure list expressions and operations; JSON execution still requires the native SDK. Lists retain their arena lifetime, and their storage contributes to allocation accounting; the per-list bound does not bound total process memory.

Record list example

type User:
  name: String
  bio: String?

type Directory:
  users: User[]

fn name_at(users: User[], index: Int) -> String:
  user = list_get(users, index) or return "Missing"
  return user.name

fn main():
  empty: User[] = []
  directory = Directory(users: [User(name: "Ada", bio: some("Engineer")), User(name: "Erwin", bio: none)])
  print(len(directory.users))
  print(name_at(directory.users, 1))
  second = list_get(directory.users, 1) or User(name: "Unknown", bio: none)
  print(second.bio or "No biography")
  print(name_at(directory.users, 9))
  print(len(empty))

For native API input, a record such as Directory decodes JSON shaped like {"users":[{"name":"Ada","bio":null}]}. Use req.json(Directory) or parse_json(text, Directory) and explicitly handle errors. json_encode(directory.users) emits an array of objects. The browser runs the pure example above but rejects JSON execution.

Optional values

Int?, Bool?, String?, RecordName? and EnumName? represent a value that may be absent. some(value) constructs a present value. Plain T does not automatically become T?: write some(value) explicitly. none has no standalone type; it needs an expected Optional type from a typed binding, assignment, function parameter/return, record constructor field or equality with a typed Optional. value = none alone is rejected.

type User:
  name: String
  bio: String?

fn describe(user: User) -> String:
  return user.bio or "No biography yet"

fn main():
  first = User(name: "Erwin", bio: none)
  second = User(name: "Erwin", bio: some("Builds native APIs"))
  print(describe(first))
  print(describe(second))

Constructors still require every field exactly once, including Optional fields; use none when absent. An Optional field may be omitted from a JSON document, which is a separate decoding rule. A mutable Optional binding may be replaced with some(...) or none without changing its type.

optional or fallback returns the contained T when present and evaluates the fallback only when absent. or return value exits the enclosing function with success; or fail "message" requires a fallible enclosing function. An Optional is not a Boolean condition, arithmetic operand or direct record-field receiver: handle absence before those uses. Optional equality supports values of the same type and comparisons with none, in either order; none == none has no inferred type and is rejected. Equality does not narrow a binding's type inside an if block.

Function results may combine the modifiers as T?!, meaning a fallible Optional. Handle the error first, then absence: (lookup() or fail "Lookup failed") or fallback. A single or handles one layer only. or return inside a fallible function returns success, just like an explicit return. The returned value must match the enclosing success type, not the unwrapped left operand. For T?!, returning none or some(value) handles the enclosing Optional result; it does not implicitly unwrap absence. Nested optionals (T??, some(some(value))), Void?, Request? and Response? are rejected. Optional values do not introduce null pointers or bypass arena lifetimes.

Errors and pipes

The ! suffix declares a fallible result, including scalar, record, enum, Optional and Response results. return value returns success; fail "message" returns an error. parse_int(String) returns Int!. Handle errors with or fallback, or return value, or or fail "message". The last form requires a fallible enclosing function. or return value inside a fallible function produces a successful result. The left expression runs once; the recovery expression runs only on error or absence. Recovery does not skip subsequent error/absence layers. Error binding/block syntax (or err:) is a design proposal, not implemented.

fn positive(text: String) -> Int!:
  n = parse_int(text) or fail "Expected an integer"
  if n < 1:
    fail "Must be positive"
  return n

fn describe(text: String) -> String:
  n = positive(text) or return "Invalid input"
  return n |> str
fn parse_or_default(text: String) -> Int!:
  number = parse_int(text) or return 7
  return number

fn main():
  print(parse_or_default("invalid") or -1)

This prints 7: the fallback is a successful return, so the caller's or -1 does not run. Use or fail "message" when failure should propagate instead. Fallible fallback expressions must themselves be handled explicitly.

value |> f(a) means f(value, a). Evaluation occurs once and in source order. The compiler checks each stage. A fallible stage must be handled explicitly before feeding a plain value to the next function; automatic result lifting is not implemented. Pipe/recovery continuation lines start with |>/or and are indented two spaces beyond the statement start. Tabs remain forbidden.

Boolean and, or, not short-circuit; legacy &&, ||, ! remain accepted. or is resolved by the left operand's type: Bool uses lazy logical OR; a fallible value uses lazy error recovery; an Optional uses lazy absence recovery. Parenthesize mixed recovery/Boolean/pipeline expressions rather than relying on precedence in the preview. not binds tightly like legacy !. Arithmetic/comparison precedences follow conventional C-style precedence; pipe has lower precedence. The future grammar will regularize these rules before stabilization.

JSON and HTTP

CallResultContract
parse_json(text, User)User!Decode JSON into a declared record type
parse_json(text, OrderState)OrderState!Decode an exact case-name JSON string into a declared enum type
req.json(User)User!Validate a JSON media type and UTF-8, then decode the request body
req.json(OrderState)OrderState!Apply the same media-type/body checks, then decode an exact enum JSON string
req.query(String)String?!Bounded, decoded query value; error and absence are separate
req.header(String)String?!Bounded, case-insensitive request-header lookup; error and absence are separate
req.param(String)String?!routing implementation: bounded decoded route parameter; error and absence are separate
json_encode(value)String!Encode a scalar, enum, list, record or typed Optional, bounded to 1 MiB
json_response(status, value)Response!Encode a scalar, enum, list, record or typed Optional with JSON content type
text_response(status, text)ResponsePlain-text response
response_header(response, name, value)Response!routing implementation: immutable addition of one validated custom response header
serve_http(port, handler)VoidNamed handler with signature fn(Request) -> Response
serve(port, handler)VoidLegacy named handler with signature fn(String) -> String

JSON input is bounded to 1 MiB. Decoding rejects missing or null required fields, duplicate or unknown fields, wrong field types, integer overflow and trailing/malformed input. An omitted or JSON-null Optional field becomes none; a correctly typed present value becomes some(value). Duplicate Optional fields are rejected even if the first value is null. Encoding an Optional emits its contained JSON value or null, and keeps absent record fields as explicit null rather than omitting them. JSON null is a data representation; there is no null literal in ThreadOne. Direct encoding requires a known type: json_encode(none) is rejected, while value: String? = none followed by json_encode(value) is accepted. Schema decoding checks structure, not domain rules such as email validity. Encoding uses a bounded writer that stops before exceeding 1 MiB. Response status values are restricted to 200–599. Invalid literal statuses are compiler errors. An invalid dynamic status passed to text_response raises a handler panic (500 within HTTP); json_response returns an error.

Request has readonly String fields method, path, body and content_type. The path excludes the query string and keeps its raw spelling. Request and Response are built-in types, not user-constructible records. The published 0.11.0 uses exact routes and query/header lookup. The routing implementation adds path parameters and response headers as specified below. Reading request metadata does not implement authentication.

type User:
  name: String
  email: String
  bio: String?

route POST "/users" (req):
  user = req.json(User) or return 400 "Invalid JSON"
  return 201 user

route GET "/health" (req):
  return 200 "ok"

Route methods and paths are literals. Routes support the bounded segment patterns described below. Duplicate routes are rejected. HEAD falls back to GET unless an explicit HEAD route exists in the selected path group. Unknown paths return 404; wrong methods on known paths return 405 with resource-specific Allow. Routes synthesize an entry point on port 8080, configurable with THREADONE_PORT and THREADONE_BIND. A route program cannot also declare main. For a custom handler or code-selected port, use an explicit main and serve_http instead.

return 201 value is Response-returning shorthand: String becomes plain text; Int, Bool, enum values, lists, records and typed Optionals become JSON (including JSON null for none). Failed JSON serialization becomes a 500 response. or return 400 "Invalid JSON" handles decoding failures inside a route. A normal json_response call allows explicit error recovery. The example echoes a user and does not perform database persistence.

The HTTP parser accepts GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS. Content-Length bodies are bounded to 1 MiB and must be UTF-8. Duplicate Content-Length and conflicting framing are rejected. Transfer-Encoding is unsupported (501); Expect is unsupported (417). Keep-alive, partial input/output and ordered pipelining are implemented. HEAD suppresses response bytes while preserving the would-be body length, including parser rejections after a recognized HEAD method and leading empty lines; 204/304 omit both body and Content-Length. Built-in TLS, chunked transfer, HTTP/2, HTTP/3 and WebSocket are not implemented.

Legacy serve receives the request target including query string. It supports GET/HEAD without request bodies and returns status 200 with plain-text content type. Existing legacy programs do not gain the new Request API automatically.

Read query parameters and request headers

Native req.query(name) and req.header(name) return String?!: a successful lookup yields some(text), a missing value yields none, and malformed or ambiguous input yields an error. Empty text is present. Handle the error first, then recover from absence separately. The example returns JSON with a q field and an Optional request_id; it never reads or echoes an Authorization header.

type SearchResult:
  q: String
  request_id: String?

route GET "/search" (req):
  query = req.query("q") or return 400 "Invalid query"
  request_id = req.header("X-Request-ID") or return 400 "Invalid request header"
  term = query or "all"
  return 200 SearchResult(q: term, request_id: request_id)

Run examples/request-access.one with the native SDK and request /search?q=hello+world with an optional X-Request-ID header. A missing q uses "all"; ?q= preserves the empty string. A missing request ID is JSON null. The example selects status 400 for lookup errors; query decoding is performed only when req.query is called and does not automatically reject requests elsewhere.

Header names must be ASCII HTTP tokens of 1–128 bytes and are matched case-insensitively. The parsed value has surrounding spaces and tabs trimmed, must be UTF-8, and is limited to 8,192 bytes after that trimming. A duplicate requested header is an error, even when the values match; values are not joined or selected arbitrarily. Missing means none, while a present empty value means some(""). Error messages omit header values. Existing HTTP parsing and framing rules still apply.

Query lookup uses form decoding: + becomes a space, percent escapes are decoded exactly once, and decoded text must be UTF-8. Split on & and the first = in each nonempty segment; a segment without = has an empty value, and empty segments are ignored. Lookup names are case-sensitive, nonempty and at most 256 UTF-8 bytes. The raw query is limited to 8,192 bytes and 64 nonempty segments; decoded keys are limited to 256 bytes and values to 4,096 bytes. Every segment is validated, so malformed escapes, invalid UTF-8 or an oversized component in an unrelated segment also fail the lookup. Duplicate requested decoded keys are errors, including equivalent spellings such as q and %71. Error messages omit query values.

These methods work with native Request handlers and routes. The browser Check operation accepts and type-checks them, but browser Run does not execute HTTP routes or request lookups. Returned text belongs to the current request arena and survives cooperative suspension within that request. Reading Authorization or another header does not validate credentials or implement access control.

Path parameters — routing implementation

Routes support whole-segment route parameters, for example route GET "/users/:id" (req):. Each parameter captures exactly one nonempty raw path segment. Parameter names are case-sensitive ASCII identifiers ([A-Za-z_][A-Za-z0-9_]*), limited to 64 bytes, and must be unique within a pattern. A route has at most 16 parameters and its pattern is limited to 4,096 UTF-8 bytes. Only a segment starting with : introduces a parameter; literal:colon remains static text. Wildcards, optional segments and partial-segment captures are unsupported. Leading/trailing slashes and case remain significant; static segments are compared without percent decoding.

Matching selects the most specific path shape before selecting a method. At the first segment where specificity differs, a literal segment outranks a parameter; declaration order is irrelevant. For example, /users/me wins over /users/:id. If the static path does not support the requested method, the result is 405 even if a less-specific parameter route supports it. HEAD uses an explicit HEAD route from the winning group, otherwise its GET route. Allow contains the winning group's sorted methods plus HEAD when GET exists. Unknown paths return 404. Two routes with the same method and canonical path shape, such as GET /users/:id and GET /users/:name, are rejected.

After selecting the path group, the router validates all captured segments before method dispatch. Invalid captures therefore return 400 even when that group does not support the requested method; the HTTP parser may reject an unsupported verb earlier. Percent escapes decode exactly once, + stays literal, and the result must be UTF-8 with at most 4,096 bytes. Invalid escapes, invalid UTF-8, decoded / or \, control characters, and values equal to . or .. return a generic 400. A double-escaped %252F is the text %2F, not a second decode. Static path matching retains its raw semantics. These rules are separate from query form decoding and do not authorize the selected resource.

req.param(name) -> String?! returns some(text) for a captured parameter and none for a valid name that is absent. The lookup name obeys the same identifier/64-byte rules; an invalid lookup name is an error. Explicit serve_http handlers have no matched pattern, so valid lookups return none. Handle errors first, then Optional absence. Returned text is owned by the request arena and remains valid across cooperative suspension. Errors omit parameter values.

route GET "/users/:id" (req):
  found = req.param("id") or return 400 "Invalid user ID"
  id = found or return 404 "Missing user ID"
  return 200 id

Response headers — routing implementation

response_header(response: Response, name: String, value: String) -> Response! creates an immutable response value containing one additional custom header. The original response remains unchanged. The result must be handled before returning it or adding another header. Text/JSON response constructors continue to choose content type and body encoding.

route GET "/health" (req):
  response = text_response(200, "ok")
  return response_header(response, "Cache-Control", "no-store") or return 500 "Header failed"

Custom headers are limited to 16 fields and 8,192 total bytes, counting every name, : separator, value and CRLF. Names are ASCII HTTP tokens of 1–128 bytes. Values may be empty, are limited to 4,096 bytes, and allow only visible ASCII (0x20–0x7E) or horizontal tab (0x09). CR/LF, other controls, DEL and non-ASCII are rejected. Names cannot repeat, case-insensitively; this API neither appends nor replaces existing headers, and cannot emit repeated Set-Cookie fields.

The following names are runtime-owned and rejected case-insensitively: Content-Type, Content-Length, Connection, Transfer-Encoding, Trailer, Upgrade, Keep-Alive, Proxy-Connection, Allow and X-Content-Type-Options. Framing and generated Allow remain runtime-controlled. Header errors are static messages without the rejected values. HEAD suppression, 204/304 body and Content-Length omission, and 205 zero-length behavior remain in effect. Custom header validation does not add streaming, TLS, authentication or broader protocol conformance.

Run examples/http-routing.one with a matching native SDK for a JSON example that retains a path parameter across a timer and adds Cache-Control/X-Route. Browser Check accepts these APIs; browser Run does not execute HTTP routes, request lookups or response-header operations. Source documentation alone is not an installed-artifact or cross-platform validation result.

Other built-ins

print(scalar or enum), str(scalar or enum), len(String or list), list_get(list, Int), trim(String), assert(Bool), arg(Int), parse_int(String). arg(0) reads the first argument to a compiled binary, or returns an empty string when missing.

CallResultBehavior
env(String)String!Environment value; missing/non-UTF8 is an error
sleep(Int)Bool!Cooperative timer, 0–60000 ms inclusive
yield_now()VoidCooperative yield
redis_ping()String!PING
redis_get(String)String!UTF-8 value; missing is an error (compatibility API)
redis_find(String)String?!UTF-8 value when present, none when missing, error on command/decoding failure
redis_set(String,String,Int)Bool!SET with positive millisecond TTL
redis_delete(String)Int!Number of removed keys

Redis uses THREADONE_REDIS_URL, verified TLS by default. Plaintext requires explicit loopback opt-in. One process-wide multiplexed connection has bounded command admission; there is no language-level pool configuration yet. Values returned by redis_get, redis_find and redis_ping are checked against 1 MiB after the driver decodes them, so this is not a bound on allocations for an untrusted Redis response. Use a trusted server. Connection/operation failures are redacted; write outcomes may be unknown. See README.md and the adapter source for exact limits. redis_find uses the fallible-Optional result: missing keys are successful absence, present UTF-8 values are present Optionals, and connection/protocol failures, invalid UTF-8 or values over 1 MiB are errors. GET/find/SET/DEL reject keys over 4096 UTF-8 bytes before connection initialization; SET also rejects values over 1 MiB. TTL is positive signed milliseconds; the server may reject an expiry that overflows its absolute timestamp. Empty text is present, not absent. redis_get keeps its original String! contract, including an error for a missing key. Binary values, pubsub/cluster/Lua/transactions and full Dragonfly compatibility remain unverified. SQL Server does not yet have a language binding. PostgreSQL, MySQL/MariaDB and MongoDB bindings are described below.

Separate cache misses from failures

fn cached_text(key: String) -> String:
  result = redis_find(key) or return "Cache unavailable"
  return result or "Cache miss"

fn main():
  print(cached_text("threadone:example"))

The first or handles the error layer of String?!. The second handles an absent key after a successful command. Neither fallback runs for a present value. These messages are application choices; the library does not classify every failure into typed error variants yet. Both reads use the same cooperative connection and deadline behavior. See examples/redis-optional.one for an SDK example.

Memory and execution

String values are immutable references into an implicit arena; record and present Optional fields preserve those lifetimes. Generated function signatures carry the arena lifetime internally. Each HTTP request owns an arena retained across suspension. Its handler future is dropped before the arena on timeout, cancellation or completion; the response is copied into the bounded output buffer. JSON decoding temporarily owns deserialized values before copying strings into the arena. Logical string allocation budget: 8 MiB per request; CLI main region: 64 MiB. These limits do not bound total process RSS: task frames, socket buffers, JSON intermediates, driver allocations and allocator overhead are separate. No globals, captured tasks or cross-request references exist yet. There is no tracing garbage collector or runtime JIT.

The executor uses Tokio current_thread + LocalSet and readiness-based I/O (Mio underneath), not io_uring. Functions lower to Rust stackless futures. Calls suspend implicitly; recursive call targets are boxed to give finite future sizes. Short acyclic calls use concrete futures; long chains insert boxing boundaries to keep application-future nesting below 24 levels. HTTP dispatch uses one boxed handler future. This is not zero-allocation async. Long computations block the event loop; yield_now() is an explicit cooperative scheduling point. There is no spawn/join, cross-core execution or user-visible task cancellation API yet.

The body deadline uses THREADONE_BODY_TIMEOUT_MS (default 10000, clamped 100–60000); expiry returns 408. Handler deadlines use THREADONE_HANDLER_TIMEOUT_MS (default 30000, clamped 1–300000); expiry returns 504. Both close the connection. Non-yielding CPU code cannot be preempted by a cooperative deadline. Panic isolation catches ordinary handler panics, not process-aborting failures such as stack exhaustion.

Accept errors retry after a cooperative 100 ms delay, logging listener_retry without error details. Existing clients, task cleanup and shutdown remain active during backoff. Persistent errors retry until shutdown; this is not a health/readiness or guaranteed recovery contract.

Browser execution preview (0.14.0 Developer Preview)

The browser Run entry uses the same parser and type checker, then interprets the checked AST in Rust/WASM inside a dedicated Worker. Native SDK commands still compile to Rust/LLVM; their execution model is unchanged. Browser execution supports a bounded pure subset: scalar expressions, checked arithmetic, functions, branches, loops, nominal enums, immutable lists, immutable records, Optionals and explicit fallible recovery. Unsupported host APIs return errors when executed; Run does not simulate I/O success. Imports and HTTP routes require the native SDK. Captured stdout and runtime diagnostics are separate, preserving output produced before an error. Source and stdout are bounded to 64 KiB, execution to 100,000 steps, cumulative string/record/list allocation to 1 MiB and calls to depth 64; the UI also enforces a wall deadline and Stop by terminating the Worker. These limits are preview safeguards, not a security certification or performance comparison.

PostgreSQL native binding (0.15.0 Developer Preview)

PostgreSQL calls use verified TLS and suspend cooperatively without await. They run only in native applications; browser Check accepts supported syntax, while browser Run reports unsupported database execution. Version 0.16.0 reuses a bounded verified-TLS pool. Version 0.17.0 adds scoped transactions below; multi-row result lists remain unsupported.

SyntaxResultMeaning
postgres_find(sql, RecordType)RecordType?!Parameter-free single-record query
postgres_find(sql, parameters, RecordType)RecordType?!Query with bound parameter-record fields
postgres_execute(sql)Int!Parameter-free statement; affected-row count
postgres_execute(sql, parameters)Int!Statement with bound parameter-record fields; affected-row count

sql is a String and each call accepts a single statement. RecordType names a declared record type. Parameter records and result records support only flat Int, Bool, String, and Optional forms of those scalars. The parameter record's declaration order maps to $1, $2, and so on, independent of constructor argument order. Values travel separately from SQL; placeholders cannot substitute identifiers or SQL keywords.

The integer codec accepts PostgreSQL SMALLINT, INTEGER and BIGINT. Reads widen to signed 64-bit Int; writes to smaller integer types reject out-of-range values. Bool accepts BOOLEAN. String accepts TEXT or VARCHAR and preserves UTF-8 and empty text. There is no implicit coercion of numeric, timestamp, binary, array, domain or enum types into these scalars.

Optional parameter values retain their declared scalar kind even when none: Int? none cannot bind to a TEXT placeholder, for example. PostgreSQL must infer each placeholder's supported type from the statement or an explicit SQL cast. Result column count, order, names and scalar kinds must match the result record, including for a zero-row query. NULL is valid only for an Optional result field; it becomes none. Non-NULL empty text remains some("").

postgres_find distinguishes three layers: a database failure is the fallible error; zero rows is a successful outer none; one row is some(record), whose Optional fields separately represent SQL NULL. More than one row is an error. Handle the error before the missing-row case:

type UserKey:
  id: Int

type DatabaseUser:
  id: Int
  name: String
  bio: String?

fn database_user_name(id: Int) -> String:
  result = postgres_find("SELECT id, name, bio FROM threadone_users WHERE id = $1", UserKey(id: id), DatabaseUser) or return "Database unavailable"
  user = result or return "User not found"
  return user.name

fn main():
  print(database_user_name(42))

The example requires an explicitly configured database and matching table. These fallback messages are application choices; the language does not yet expose structured SQLSTATE errors. postgres_execute rejects statements returning columns, including RETURNING. For a single returned row, use postgres_find with a matching result record. A write may already have applied even if its RETURNING result later fails decoding or exceeds a limit.

Configure THREADONE_POSTGRES_URL outside source. Optional THREADONE_POSTGRES_CA_PEM contains private CA certificate PEM text; chain and hostname checks remain enabled. Unix-socket and host-address-only configurations are rejected. Outside a transaction callback, each binding call leases and resets an exclusive pooled session, so temporary tables, session settings and BEGIN/COMMIT state do not persist across calls. There are no automatic statement retries.

BoundLimit
Shared active calls / waiting calls8 active, at most 32 waiting
Admission deadline5 seconds; failure means the binding operation did not start
Statement deadline5 seconds; acquisition includes connection work, and successful reset has a separate 5-second budget
Connection URL / CA PEM16 KiB / 64 KiB
SQL textNonempty, at most 64 KiB UTF-8
ParametersAt most 64; aggregate String payload at most 1 MiB
Result columns1–64; unique nonempty names, at most 256 UTF-8 bytes each
Find resultAt most one row and 1 MiB decoded scalar payload

The result budget counts string UTF-8 bytes, eight bytes for each Int and one byte for each Bool or NULL. It applies after driver decoding and before copying text into the request/application arena; it does not cap wire allocation, metadata, TLS buffers or total process RSS. Returned strings retain their arena lifetime across cooperative suspension. Arena capacity is checked before copying the result row, so quota exhaustion does not copy a partial row.

The admission and operation deadlines are separate. An HTTP handler can impose an earlier deadline. Failure, timeout or cancellation disposes the session and releases local admission capacity; it does not prove that server-side work stopped or that an applied write rolled back. Reconcile unknown write outcomes using application state or an explicit idempotency strategy. Broader types, streaming and other database bindings remain separate work. See examples/postgres.one, its setup notes, and the versioned release report for actual tested platforms and fixtures.

PostgreSQL pooled calls (0.16.0)

The native process lazily initializes one pool from THREADONE_POSTGRES_URL and optional THREADONE_POSTGRES_CA_PEM. After valid construction, configuration is fixed for that process; restart to change it. At most 8 sessions are leased or idle, with 32 queued acquisitions. Acquisition has one 5-second budget covering queue, health probe and TLS/auth connect; statements have 5 seconds and successful reset adds at most 5 seconds. Idle expiry 60 seconds and maximum age 300 seconds are checked lazily on checkout/return, not by an idle timer.

Outside a transaction callback, a successful call performs ROLLBACK then DISCARD ALL before returning its connection. Session settings, temporary objects, prepared statements and advisory locks do not cross calls. A reset failure discards the connection while retaining a known-successful statement result; no statement is retried. Failed/cancelled operations discard their lease. Writes can already have applied when a caller is cancelled. Raw BEGIN/COMMIT calls still cannot create a transaction spanning language calls.

The Rust adapter exposes bounded close with a1-second default grace, immediate admission closure and idle cleanup, then forced invalidation of held sessions. Language programs rely on runtime/process shutdown; there is no .one pool configuration/close or escaping transaction-handle API. Pooling is not a throughput claim or production-readiness certification.

Scoped PostgreSQL transactions (0.17.0)

postgres_transaction(handler) or postgres_transaction(handler, paramsRecord) returns Bool!. The handler must be a named function returning Bool!, with zero parameters or one matching record parameter. The argument expression is evaluated once before beginning. Nested transactions are rejected and poison the outer transaction, even if their error is caught. No transaction handle can escape.

Within the callback, postgres_find and postgres_execute use one exclusive transaction session. Every successful handler result commits, including false; use fail to request rollback. A failed database operation, including client validation or result decoding, prevents commit even when its error is recovered inside the handler. A business error recovered before returning a successful result can still commit. Arbitrary non-database effects (HTTP/Redis/output) are not rolled back.

Default isolation is PostgreSQL READ COMMITTED, read/write. A single prepared SELECT, INSERT, UPDATE, DELETE or WITH statement is allowed per call. DDL, explicit BEGIN/COMMIT/ROLLBACK, CALL, DO and session commands are rejected inside the callback. Create schema outside it. This SQL boundary is not a security sandbox; use trusted SQL and bound values. Rust adapter isolation/read-only options are not exposed in this language API.

Ownership is Tokio task-local rather than thread-local, so concurrent HTTP requests cannot share a transaction. Nested calls to ordinary functions retain the current transaction. Total wrapper budget is30 seconds including acquisition and cleanup; statement operations are bounded to5 seconds and an HTTP handler may cancel earlier. PostgreSQL local statement/idle transaction timeouts supplement the client deadline. Cancellation disconnects and discards; it does not prove immediate server termination. Deadlines require the cooperative executor to run and are not a hard real-time guarantee.

Commit and rollback consume ownership. After acknowledged commit/rollback, the expiration task is stopped and joined before session reset/reuse. Failed cleanup discards the connection but preserves a known successful commit result. If COMMIT may have reached the server and its reply is lost or cancelled, outcome is unknown. No statement or transaction is automatically retried. See examples/postgres-transaction.one and versioned real-fixture evidence.

MySQL/MariaDB single-record operations (0.18.0)

mysql_find(sql, [parametersRecord,] ResultRecord) -> ResultRecord?! distinguishes absence from errors. mysql_execute(sql [, parametersRecord]) -> Int! returns affected rows and rejects result-producing statements. Use positional ? placeholders: parameter fields bind in declaration order. Supported client values are Int, Bool, String and scalar Optional; NULL retains its client kind but MySQL protocol sends untyped NULL. Server SQL modes and column types may coerce parameters. Bound values prevent value interpolation, not target-column schema errors.

Result columns must exactly match record field order/names/types even when no rows return. Integer results must fit signed64bit. Bool requires TINYINT(1) metadata and values0/1. Text is converted by the server to utf8mb4 then UTF8 validated. Binary charset, native JSON type, ENUM/SET, date/time, decimal and floating-point results are rejected. MariaDB JSON aliases advertised as LONGTEXT are text, not a JSON codec. Optional accepts NULL; required fields reject it.

Each call opens a verified-TLS session using external THREADONE_MYSQL_URL and optional THREADONE_MYSQL_CA_PEM (certificate text). No plaintext opt-in or Unix-socket fallback. Limits:8active calls/32pending,5s admission and5s connect+statement; SQL64KiB,64parameters/1MiB aggregate text,1row/1MiB decoded result,64columns/names256bytes. Results are bounded after driver decoding, before cumulative arena copying; no total wire-memory guarantee. Successful sessions close with a bounded cleanup; failed/cancelled statements discard. Client cancellation does not prove immediate server termination, and an applied write can have unknown outcome. No automatic retry.

One prepared SELECT/INSERT/UPDATE/DELETE/WITH/CREATE/ALTER/DROP/TRUNCATE statement is permitted; CALL, explicit transaction control and executable comments are rejected. No MySQL connection pool, transaction callback, streaming or multi-row list API is exposed. PostgreSQL transaction callbacks do not include MySQL operations. Native execution only; browser Check handles syntax and Run reports unsupported database calls. Actual server/platform and exact artifact evidence is recorded separately.

MySQL handshake cancellation may invoke upstream driver cleanup tasks that this adapter cannot directly track. Eight active calls is not a global cap on server connections or all background cleanup tasks. Prepared statement caching is limited to32 per session; cleanup does not retry an application statement.

MongoDB typed documents

mongodb_find(collection: String, id: String, RecordType) -> RecordType?! looks up one exact String _id, separating a successful absence from schema/transport errors. mongodb_insert(collection, record) -> String! returns the supplied _id; mongodb_replace(collection, record) -> Int! returns matched count 0/1, including unchanged matches, and never upserts; mongodb_delete(collection, id) -> Int! returns deleted count 0/1. Insert duplicate IDs are errors. Replace overwrites the complete document, not a $set patch. No arbitrary query/operator documents, projection, multi-document lists, aggregation, session or transaction API is exposed.

A record has 1–64 unique ASCII identifier fields of at most 64 bytes, including required non-Optional _id: String. Other fields support Int, Bool, String and scalar Optional. Int writes use BSON Int64; reads accept Int64 exactly or losslessly widen Int32. Bool accepts only BSON Boolean, not numeric 0/1; String accepts only BSON String. Optional none writes BSON NULL; reads of missing Optional fields and BSON NULL both become none. Missing required fields, unknown fields and unsupported BSON types are errors. Field order does not matter. No ObjectId, decimal/float, date/time, binary, nested document or array conversion is performed.

Required environment configuration is THREADONE_MONGODB_URL (at most 16 KiB) plus THREADONE_MONGODB_DATABASE (nonempty, fewer than 64 UTF-8 bytes with namespace validation). TLS verifies certificates/hostnames; private trust roots can use the URI's tlsCAFile path. Insecure TLS flags and unacknowledged w=0 writes are rejected. The first successful initialization retains its shared client/configuration until process exit; changing environment configuration requires a new process. Eight active calls and 32 waiting slots share process-wide admission. Admission has a 5-second deadline, followed by a 5-second initialization/operation deadline. Failed initialization can be attempted by a later explicit call, but document writes are never automatically retried.

Collections are nonempty Strings of at most 128 UTF-8 bytes, with no NUL or $. _id is a nonempty application-supplied String of at most 256 UTF-8 bytes, with no NUL. Strings that look like query operators remain literal BSON values. Document encoding preflights the exact 1 MiB BSON bound, including field names/overhead, before copying String payloads. Read document bounds apply after driver decoding; the accepted row's complete String payload is checked against cumulative arena capacity before arena copies. These bounds do not cap all driver allocations or total process memory.

The shared MongoDB driver owns background topology work and per-server pools (maximum 8 connections, minimum 0, at most 2 connecting per server); monitoring connections are additional. Application admission is not a global server-connection/work or driver-task cap. Cancelled command futures discard unfinished pooled connections asynchronously, but cancellation or a lost response can hide an already-applied write and does not prove immediate server cancellation. There is no automatic write retry; reconcile by _id first. PostgreSQL transactions do not cover MongoDB calls. Timers are cooperative. Browser Check handles syntax; Run rejects database execution. See examples/mongodb-README.md and the matching release report for actual server/platform and exact-artifact evidence.