Skip to content

Standard library

Alias the gale_std modules you use. Public signatures are ordinary Gale interfaces, with the same contracts/compiler facilities available to user code. Expected checked failures are explicit Result values; external-world operations remain effectful observations.

Elixir names and behavior are a preference, not an inclusion requirement. One gale_std namespace combines Gale-specific APIs such as decode with selected Elixir and Erlang facilities. Implementations may draw from both native libraries while preserving the declared types and proof boundary.

Need Modules
Optional/fallible values option, result
Numeric primitives/conversions kernel, integer, float, number
Text/bytes/bits/atoms string, binary, atom
Collections list, map, map_set, keyword, stream
Dynamic input/JSON decode, validation, json; gale_schema for schemas
Files/output/logging file, path, io, inspect, logger
OS/clocks/dates/URI/crypto system, node, date, date_time, naive_date_time, uri, crypto
Processes/services/resources process, otp, gen_server, supervisor, application, task, task_supervisor, dynamic_supervisor, registry, ets, persistent_term
Tests test

Option retains Some/None with map/and_then/flatten/fallback and nil conversions. Result retains Ok/Error with map/map_error/and_then/fallback. Callbacks returning Result are ordinary values unless an API explicitly sequences them. with unwraps Ok at each step and wraps its final expression; it does not implicitly flatten. A present nil inside Some differs from absence.

List/Map helpers publish content-level contracts as well as structural bounds. Safe access returns Option so an actual nil element is distinguishable from absence. Supported operations retain native negative-index/count semantics; invalid configuration uses the operation’s checked error interface.

Family Required successful-value contract
List append/subtract/reverse Exact order/content; subtraction removes the corresponding first strict occurrences, not set difference.
map/filter/reject Exact callback/content relations; filter preserves order.
flat_map Empty input returns empty; singleton results satisfy the callback contract. General concatenation and callback order are runtime-tested behavior.
reduce/reduce_while/map_reduce/scan Accumulator relation in the actual traversal order; halt stops at the declared point.
first/last/at/find Some contains the corresponding element; None denotes absence, not a nil payload.
take/drop/split/take_while/drop_while Exact admitted native prefix/suffix and negative-count behavior.
concat Concatenates one level only. No recursively heterogeneous flattening.
duplicate/chunk_every Duplicate count >=0; chunk size >0; otherwise checked invalid-count error. Chunks concatenate back to the input.
zip/zip_with/unzip Shorter-input zip length; exact positional pairing/projections.
with_index/intersperse Zero-based positions; separators only between elements.
sum/product Exact Integer folds, identities 0 and 1; no unchecked Float aggregate.
uniq/dedup First strict occurrence versus consecutive strict runs; preserve the appropriate input order.
frequencies/group_by Strict keys, occurrence counts and stable group contents; no map iteration order. group_by keys require a pure callback like selection predicates.
map_join Exact concatenated String bytes and separators; no additive grapheme-length theorem.

list.find exposes an exact checked first-match model. Its result is the earliest element satisfying the pure predicate, or None when no element does. The implementation must prove that relation independently of callers.

string.join(parts, separator) is a pure native Enum.join binding with an exact checked contents model. Empty inputs produce ""; a singleton is unchanged; longer inputs insert the separator only between elements, including empty elements. These are byte-content guarantees, not additive grapheme lengths.

list.map publishes the predicate list.mapped(values, transform, result). It relates each input/output pair through call_ensures, preserving callback contracts for ordinary callbacks and deterministic results for checked pure callbacks. Its private recursive model is checked independently; callers use the public contract. Output length is preserved in both cases.

list.reduce publishes list.reduced(values, initial, stepper, result). It describes the ordered accumulator updates through call_ensures, returning initial for an empty input. A separate checked postcondition exposes that empty-input equality directly to callers. Intermediate states are erased proof witnesses; the implementation remains tail recursive.

list.flat_map proves the empty-input result and the callback’s invocation contract for a singleton input. It accepts ordinary effectful callbacks. The implementation concatenates one returned list per input in order, including empty chunks; runtime tests cover these contents and callback traces. Exact concatenation for longer inputs is outside the release proof interface.

list.map_reduce retains ordinary callbacks and native Enum execution. Its normal-return contract relates one output per input and the accumulator passed between consecutive invocations, in input order, through call_ensures. Intermediate accumulator values are an erased proof witness. Empty input returns {[], initial}; effects do not acquire a logical invocation or termination promise.

list.map_join relates each ordinary callback’s returned String to its input through call_ensures, then specifies exact string.join bytes in input order. Empty input produces ""; empty callback results still participate in separator placement. This establishes contents without treating an effectful callback as pure. | any/all/count/member | Exact pure predicates or strict membership; native short-circuit behavior where applicable. |

list.split_with is a stable partition: its outputs equal list.filter and list.reject using the same pure predicate. list.take_while and list.drop_while stop testing at the first false result. For [1, 3, 2] and fn(n) -> n < 3, they return [1] and [3, 2]; split_with returns {[1, 2], [3]}. Their proof contracts expose this distinction through ordinary checked recursive models while execution uses native Enum functions.

list.frequencies is a pure native observation. Its exact key set consists of the strictly present input values; every stored count equals list.occurrences(values, key). Absent values have no entry. Its contract does not impose an iteration order or a fixed size on dynamic maps.

Callback invocation contracts are general. Effectful callbacks get valid per-call and normal-return structural facts, not invented deterministic mathematical output. Do not assume map’s effect order for grouping/sorting: the native group_by implementation can visit in reverse while producing stable groups. Test the supported native behavior without promising a stronger effect trace. Duplication exposes a checked repetition definition in addition to its count and identical-element guarantees. Signed slices expose the recursive prefix definition and retain the checked partition and length laws; their contents are available without recovering a unique list from size bounds alone.

Sorting/min/max use explicit comparators and keys, not protocols or mixed native term ordering. Comparators use Order; stronger ordering guarantees require total-preorder laws. Stable sorting preserves the input multiset and relative order of equivalent keys. Publish sortedness and permutation through ordinary contracts/predicates so callers can use them. A well-typed comparator is not proof of transitivity. Use Why3 sortedness/permutation/occurrence theories through the native comparator adapter; prove comparator laws where a guarantee requires them. list.occurrences(values, value) publishes an exact checked contents equation and a bound between zero and the list length; the ordinary proof predicate list.permutation(left, right) equates those counts for every admitted value. Both sorting APIs preserve this multiset on normal return, independently of comparator ordering laws. Predicates, comparators and selection keys require pure callback interfaces. Comparator Equal means ordering equivalence, not strict identity; require coherent Less/Equal/Greater results and reversed comparisons, without false antisymmetry for distinct tied values. Extrema return Option, select the first tied original value and return None on empty input. Stability, permutation and sortedness are separate claims; do not infer one from the other two or promise comparator invocation counts. The proof predicates list.order_laws(compare), list.sorted(values, compare) and list.stable(input, output, compare) expose comparator coherence, ordered output, and preservation of each ordering-equivalence class in input order. Sorting publishes sortedness and stability when the comparator laws hold; permutation remains unconditional. Equal may relate distinct values. For sort_by, list.sorted_by(values, key, compare) and list.stable_by(input, output, key, compare) expose the same properties through the pure key function. These predicates are erased specifications; native Elixir performs the sorting. The ordinary extrema contracts also publish exact empty-input classification and original-member selection, independently of comparator ordering laws. Native minimum/maximum calls are reached only after the checked nonempty branch. The wrappers call native Enum externs with the supplied comparator. The maintained proof contracts establish empty-input classification and membership; they do not establish extremality or tie selection.

Integer ranges are native language values: first..last, first..last//step, and bare .. construct the built-in Range struct with Integer fields first, last, and step. in / not in support range membership. No gale_std.range module is required. Native direction, step and empty-range semantics follow Elixir. Literal zero steps are rejected; dynamic steps retain nonzero-step verification obligations and native errors. Materialized list.range/3 returns Error(:invalid_step) for zero. There is no generic Enumerable/protocol abstraction.

Map get/2 returns Option; get/3 takes an eager default. Put/update/delete/pop, get_and_update, filtering and merge retain native key-presence/callback semantics. Merge publishes the exact key union and right-biased values; drop/take publish exact key selection and unchanged retained values. These three operations are pure, and repeated or absent selection keys are harmless. Stored nil remains present. An empty merge input preserves the other map’s native identity even when the declared key/value domains differ. Update and its default alias call the ordinary callback once only for an existing entry, insert the eager default otherwise and preserve other entries. Filtering requires a pure predicate and publishes size/subset/unchanged-value facts. Transformations and folds permit effects; proof-only invocation-contract observations preserve their normal-return callback guarantees. Callback admission must follow from its checked interface and actual call site. Enumeration exposes exactly the entries, with no deterministic key order guarantee. Keys, values and to_list contracts must not assume separately called enumerations can be zipped into corresponding pairs without a native guarantee. from_list equates its result to a checked contents definition that inserts pairs in list order, so duplicate keys keep the last value. The function and its private accumulator prove that equation and their size bounds. An ordinary recursive helper supplies logical computation; callers do not depend on the executable accumulator’s body or special compiler handling. put_new describes the exact unchanged map or insertion, including untouched entries. Its native declaration explicitly trusts logical-call eligibility. pop publishes the optional stored value and exact deletion result; stored nil remains present and an absent key preserves the input map. The source wrapper must prove these guarantees from its lookup and deletion dependencies. keys publishes exact membership and one occurrence per present key. to_list publishes exact pair membership and occurrence counts, including stored nil. Neither contract chooses an enumeration order. values returns native typed elements, including duplicates and stored nil, with length equal to the observed input map size. Its pure native contract preserves the multiset from the second projection of list.unzip(to_list(map)). Unzip preserves both ordered projections through a checked recursive contents definition. Its separate erased multiplicity lemma preserves count guarantees without hiding the exact contents definition from callers. The erased checked list.unzip_permutation_values lemma connects counts across pair permutations. The unzip wrapper retains Enum.unzip execution and proves its count observation using checked source removal, congruence and induction facts. Native correspondence remains trusted. No dedicated public map proof API or positional correspondence with a separate key enumeration is promised. map_values preserves keys and size through an ordinary key-preserving callback contract on its native mapper. A mapper that can change keys can merge entries; its type alone does not justify unchanged cardinality. The public contract exposes that key set for ordinary effectful callbacks too. get_and_update invokes its callback once with the presence-aware Option; Keep inserts/replaces and Drop removes the target. Both preserve other entries and return the extracted callback value. Structural size/frame guarantees do not assume that an unknown callback is mathematically callable. update and get_and_update additionally relate their results to call_ensures observations of the callback. These are checked invocation relationships, including the Keep/Drop choice, rather than logical evaluation of an effectful callback. list.last exposes its exact empty, singleton and recursive-tail result relationship.

MapSet is invariant in its element type and uses new/0 and new/1 for construction. Its native representation remains opaque. Why3 finite sets model extensional contents, size, membership and set operations. Do not identify extensional equality with incidental native internal structure. to_list is unique but unordered, using strict native equality. Empty/list construction and put/delete expose cardinality and membership laws; union, intersection, difference and subset expose ordinary extensional observations. The native bridge uses Why3 finite sets over strict runtime value identity and requires a matching native representation and operation signature.

Keyword lists are List<{Atom,V}>: duplicates and order matter. get returns the first matching value as Option; put removes all old occurrences and inserts one without a promised position; delete removes every matching key. A keyword-shape predicate does not validate an arbitrary V payload. No dedicated compiler type. Ordinary content contracts expose first-match lookup (including Some(nil)), stable deletion, keys in input order and exactly one replacement entry after put. The relative order of entries with other keys is preserved.

Known interfaces use declared types; optional runtime type checkers raise when a foreign value violates them. Untrusted/dynamic data is explicitly decoded. Strict unknown-field handling is an ordinary validation failure, never a debugging exception.

Basic decoders and schema validation/encoding share an ordinary stdlib-owned ValidationError with machine-readable kind, outer-to-inner path, expected and found descriptions, and alternative context. Use Result<A, List<ValidationError>>. The shared Path uses Key(String) and Index(Integer); named error fields are kind, path, expected, found and alternatives. The trailing alternatives list defaults to [] and remains separate from the input path. gale_schema.errors.issue publishes that it preserves the supplied kind, path, expected and found text and initializes the alternative context to []. Place the shared data/formatting/accumulation interface in gale_std.validation. Its ordinary both<A,B> combines two independent validation Results into the paired value or concatenated error lists, preserving failure even for Error([]); recursive composition has no field-count limit. This also serves user libraries without special compiler behavior. collect combines a list of independent results in order, with the same failure rules. prepend_path adds an enclosing location to every error without changing alternative context. These helpers are ordinary pure Gale functions. Migrate DecodeError/DecodePath and schema Issue/Path consumers coherently. Formatting is a separate function over the complete list; callers need not parse error text. JSON syntax errors remain a distinct parsing category containing location/context. gale_schema.tagged_union(field, branches) takes {String, JsonSchema<A>} pairs and returns Result<JsonSchema<A>, List<ValidationError>>. Configuration rejects empty branches and duplicate tags. Decoding selects only the named branch; encoding and validation reject missing, wrong or ambiguous emitted tags. Tagged exports retain the configured literal discriminator in each branch. JSON Schema uses required constant tag fields; TypeScript intersects each branch with its literal tag field. Both report GenerationIssue for arbitrary transforms and runtime-only predicates. Pure validation diagnostics use structural type/value summaries for the admitted representations, without invoking arbitrary foreign Inspect/String.Chars protocols. User-facing rich inspection may be a separate effectful formatting step. Do not mark the current error formatter trusted-pure merely to make schema contracts pass.

Collect all independent field, element and predicate failures. Preserve declaration order for fields and index order for lists; use stable sorted key order for errors from dynamic string-keyed dictionaries and unknown object fields. A malformed outer container yields its shape error, not fabricated errors for inaccessible children. Refinement/constructors run only after their dependencies succeed. Strict unknown fields accumulate alongside discoverable known-field failures.

Failure is independent of error-list length: Error([]) remains failure and cannot become a successful partial collection. Accumulating combinators combine independent validation failures; ordinary and_then/with remain dependent and short-circuiting.

Nilable<T> is T | nil. The nullable helper represents JSON null with a Nilable result. Missing is represented separately through Option. Optional nullable fields retain all three states: missing, present nil and present value. Defaults apply only to missing values, not invalid/null values unless declared. Object policy defaults to Discard; the closed-object adapter explicitly selects Reject. Discard constructs only the declared output fields and proves nothing about input extras; Reject success additionally proves absence of unknown keys under that object policy. Preserve metadata is permitted only when a custom codec actually preserves extras; there is no implicit preserving object builder. Do not turn schema metadata into an implicit strictness switch or proof.

Reusable refinement without special compiler treatment

Section titled “Reusable refinement without special compiler treatment”

Decoder<A> is an ordinary function value; Schema<A,Encoded> is opaque. Its read-only validator, decoder, and encoder accessors expose pure callbacks. Combinators and explicit custom codecs construct schemas; descriptions remain a correspondence responsibility for custom codecs. Their validation, decode, encode, predicate, transform and constructor/getter callbacks must satisfy pure interfaces. Read effects before validation and pass immutable inputs; effectful Result-returning workflows remain ordinary functions outside this composable schema interface.

decode.run(value, decoder) exports the equality between its result and decoder.(value). Combinator contracts use this public relation without depending on the body of run. binary, integer, float, and boolean additionally export the corresponding runtime kind test: success implies that test and failure excludes it. string exports only that success is a binary; invalid UTF-8 remains a failure. field exports object-failure propagation, missing-key rejection, and equality with the child decoder’s successful value. optional_field exports the same object failure, Ok(None) for a missing key, and Ok(Some(value)) when the child decoder succeeds. The public gale_schema.validate, decode, and encode wrappers likewise publish equality with their corresponding stored operations; description returns its inspectable description. This forwarding guarantee does not establish codec success or a round-trip law for an arbitrary schema.

Lazy recursive schemas have the same pure/termination obligations as other schema callbacks. The thunk is not memoized. Recursive decoding/encoding must establish a decreasing structural measure on the traversed input/value; a self-looping schema is not total because it uses lazy. Exporters use explicit named references for recursive descriptions and report GenerationIssue for unsupported descriptions and unnamed lazy expansion. Naming a description does not establish termination of arbitrary thunk execution.

A refinement condition is written once as executable code, such as fn(n) -> n >= 18. The ordinary library combinator’s quantified contract relates its returned decoder to its base and predicate. For every admitted input:

  1. Base failure remains failure.
  2. Base success plus a true predicate returns that same value successfully.
  3. Base success plus a false predicate produces the refinement error.

The success implication alone is insufficient: an always-Error implementation must not satisfy the full combinator contract. Matching Ok provides the predicate fact; an assertion can check that fact but is not needed to acquire it and never re-runs the validator at runtime.

Preserve facts about particular values through local bindings, records, returned closures and contracted factories, including captured bounds. An arbitrary parameter of type Schema<Integer,Json> does not imply positivity. A factory publishes its relation once; consumers requiring it state a contract or use an opaque invariant. Rebinding/replacing a schema replaces its evidence. Branches retain only justified conditional/common facts. Transformations and arbitrary record constructors require their own output relation, not properties copied from similarly named input fields.

Implement all combinator contracts as ordinary Gale code using section 7/8 facilities. Renaming/copying a combinator into a user module must preserve its provability. Description/export metadata never supplies a theorem. No predicate type parameter, value-indexed alias, schema-name recognition or per-rule duplicate wrapper contract.

any_of selects the first successful alternative; if none succeeds, collect every branch’s failures with branch context. one_of checks all alternatives, requiring exactly one success; zero aggregates failures, multiple successes produce ambiguity. Selected branch facts do not become a conjunction of every alternative’s facts.

tagged_union performs actual discriminator dispatch, replacing metadata-only first-success search. Its configuration is an ordered list of explicit {String, Schema<A,Json>} tag/branch pairs plus a String field name, validated by an ordinary Result-returning constructor. Empty branches and duplicate tags are configuration errors. No compiler inference from descriptions or constructor names.

Branch object schemas include the discriminator in their declared shape. On decode, validate the outer object and String discriminator, select exactly the matching branch, and run that branch only. Missing/malformed/unknown tags fail at the tag path. Malformed selected payloads cannot fall through into a different branch. Strict field checking includes the discriminator as a declared field.

On encode/validate of A, branch schemas establish whether they accept that value. Exactly one branch must accept it and successfully emit an object bearing its configured discriminator value; missing/wrong tags and multiple accepted branches are errors. Do not insert an unverified tag over an arbitrary payload. Runtime tests cover that search. The exported proof facts are smaller: read_tag returns the field’s string, a missing field, or a non-string field. The validation wrapper preserves a successful tag and fails on the other two results. Discriminator-error forwarding through tagged_decode and validation of emitted tags are covered by runtime tests. Dispatch proves that an empty branch list fails and that a tag equal to the first branch returns that branch’s decode. A fact about later branches is a caller lemma; the dispatch specification does not call itself. any_of and one_of keep the runtime behavior above and are not proof roots.

JsonObject uses Map<String,Json>; arrays use List. Native text parsing preserves the supported Elixir JSON decoder’s first-textual-duplicate-wins behavior, including escaped equivalent keys. Pair-list-to-map construction remains last-pair-wins; these are different operations. Neither retains original duplicate history or key order. Tagged dispatch operates on the decoded object map. Pin native compatibility fixtures so a dependency upgrade cannot silently change proof assumptions.

JSON decode/parse accept Binary, with String accepted by subtyping. Invalid UTF-8 and unrepresentable floating-point text produce parsing errors. JsonSyntaxError preserves native {:unexpected_end, Integer}, {:invalid_byte, Integer, Integer}, and {:unexpected_sequence, Integer, Binary} tuples, with nonnegative byte offsets and invalid-byte payloads in 0..255. These native scalar facts support contracts; full grammar and numeric round-trip proofs are excluded.

json.encode(Json) -> String remains direct for the closed valid domain of finite Float, Integer, UTF-8 String, Boolean, null, arrays and object maps. Schema encode and stringify return collected errors because domain refinements/backward transforms may fail. No automatic inverse law follows from two codec function fields. Value round trips need explicit contracts and native evidence, including large numbers and signed zero; no text/whitespace/key-order/escape-spelling preservation theorem.

JSON Schema/TypeScript exporters describe supported schema structure. Unsupported custom predicates/transforms must produce GenerationIssue rather than silently advertise an exact exported validation rule. Metadata is useful documentation and interoperability data, never proof of a decoder’s behavior. Those exporters are runtime-tested. They are outside the first proof commitment because a caller composes decode, refinement, and local field facts rather than a generated document.

Pid<M> is invariant in mailbox type. AnyPid represents erased unknown processes; erasure is allowed, recovery of typed service/message capability requires an explicit trusted boundary. Runtime PID shape alone proves none of that capability or liveness.

Declare the whole intended mailbox, including custom messages and standard process messages. The stdlib supplies Down/ExitEvent/ExitReason/Monitor/Ref types with native tuple representations. Match explicit tuples; no new pattern-helper expansion syntax. Trap-exit state does not require a new capability witness.

Receive is native selective receive: it may match only selected messages; unmatched messages remain queued. An explicit wildcard consumes messages, so do not impose it to fake exhaustiveness. Branch facts require actual matching and declared assumptions about all senders. Receipt of a native-shaped DOWN/EXIT tuple does not authenticate it.

Timeouts retain 0 and :infinity with the native nonnegative bounded receive domain (0..4,294,967,295 for the selected primitive). A union alias containing Integer does not enforce the bound by itself. Reject invalid literals statically; use ordinary validation or established preconditions for dynamic values. No new dependent timeout type. check alone is not proof of a dynamic precondition. Each native wrapper uses its own documented timeout domain rather than assuming all OTP timeouts are identical.

process.flag(:trap_exit, Boolean) -> Boolean returns the previous setting. Atomic spawn_monitor returns {Pid<M>,Monitor}. Spawn/spawn_link and native link/monitor semantics remain distinct; successful creation supplies no survival or child-result guarantee.

Demonitor returns Result<Boolean,MonitorError>, with MonitorError = :invalid_argument, preserving native default options and explicit flush/info behavior. Use ordinary extern raises for the declared ArgumentError class; unrelated failures propagate. Default success can be true for an inactive reference; only :info reports whether the monitor was active. Neither result authenticates a monitor or a DOWN tuple. Flush consumes at most the native matching monitor message, not every message with a similar shape. Include checked send_after returning Result<Timer,TimerError> for the selected local PID target; a dead local target is not an invalid argument. Preserve native bounds and target-death cancellation. Timer is unparameterized; synchronous cancel_timer returns optional remaining milliseconds, including zero. Absence/remaining time does not prove whether the application saw a message. Never claim exactly-once timer delivery.

Behaviours use declares, implements and explicit mod capabilities. A module declares at most one behaviour and may implement multiple interfaces. Generic interfaces and native mappings remain. Runtime values are native modules; no protocol/typeclass search or inferred global implementation selection.

One public function can satisfy same-name/arity callbacks from several interfaces when it conforms to each independently. Check each contract under that interface’s own preconditions, never their conjunction. Preserve every conformance obligation and metadata entry. Different arities are distinct; no interface-specific hidden body.

Optional callbacks without bodies may be absent and cannot be directly called through an abstract capability lacking a guaranteed implementation. Optional callbacks with default bodies are included: omission emits a real ordinary function; an explicit implementation replaces it. Defaults resolve in their declaration’s lexical context and must satisfy the same interface contract as overrides. Conflicting applicable defaults require an explicit implementation; do not silently choose an interface. Native framework fallback is distinct from an exported function. Extern declarations do not execute use macros. No reflective optional-callback lookup API is added.

GenServer retains native callback shapes/default behavior, typed initialization, call/cast/info/continuation and state transitions. Defaults use the general behaviour mechanism or explicit adapters. Init remains required; handle_info’s native logging/state-preserving default, terminate’s no-op and native status fallback are modeled explicitly. Missing call/cast handlers retain native failure behavior; handle_continue has no invented fallback.

No hot reload, code_change callback, code-upgrade types or upgrade proof machinery. Verification assumes checked code and dependencies, not arbitrary live replacement.

Prove initialization establishes the state invariant and every normally completed transition preserves it, including continuations, hibernation, stop tuples and reply/no-reply forms that carry state. The server loop may run forever. State ADTs and relations express permitted transitions; Pid does not assert a current state.

Immediate native reply tuples and typed ReplyTo<R> support explicit/deferred reply, including stop-with-reply. Cast/info transitions do not acquire a reply payload. No linear one-reply, delivery or caller-survival guarantee. Idle timeout scheduling adds :timeout to the info domain; queued messages may cancel even zero timeouts. A received :timeout atom is not proof of elapsed time or its source.

Startup preserves distinct native outcomes: successful server, :ignore, or error. Synchronous call returns Result<Reply,CallError> with CallTimeout or CallFailed(reason: ExitReason) for native call exits. Classify the native reported reason, not measured time: a server can itself exit with a timeout-shaped reason. Cast remains fire-and-forget. Stop returns Result<:ok,StopError>, with StopTimeout and StopFailed(reason: ExitReason), default timeout infinity. Invalid supplied timeout/configuration uses the wrapper’s explicit invalid-argument case; do not relabel it as server failure. Checked catch does not block an independent linked exit signal or promise caller survival.

CallError and StopError also have InvalidArgument(argument: Term). Their timeout domain is 0..4,294,967,295 or :infinity on the selected native runtime; validate it before invoking the server. Defaults are 5000 for call and infinity for stop. Catch only the contextual native GenServer operation exit, preserving its reported reason. Ordinary callback exceptions, foreign naming callback defects and independent exit signals are not globally rescued. Native :timeout is classified as the corresponding timeout error without claiming it was caused by elapsed waiting.

otp.CallNext<R,S,C> contains the ordinary reply/no-reply/stop tuple alternatives; otp.Schedule<C> admits Timeout, :hibernate and {:continue,C}. The handle_info signature includes Info | :timeout. Its source default logs through an ordinary native adapter and returns the unchanged state; terminate’s source default returns :ok. Native format_status fallback remains an absent optional callback, rather than an invented exported function.

Naming forms include native local atoms, remote tuples, global and via addresses. Shared invariant ServerName<Service> relationships connect startup and client operations through ordinary library signatures while retaining native addresses. Registered-name helpers are explicit trusted service declarations; lookup proves neither conformance nor liveness. No new runtime wrapper struct or compiler-known server names.

gen_server.StartOption<Service> accepts native raw name options and {:name,ServerName<Service>}. start_link fixes Service to the selected implementation’s complete module capability. A typed name for another service is rejected. Raw names remain available for native interoperability; they make no static service claim. Remote client addresses are not local startup names.

Supervisor startup uses supervisor.StartOption<Service> with the same connection to its module capability. DynamicSupervisorOption<Identity>, TaskSupervisorOption<Identity> and TaskSupervisorChildOption<Identity> connect typed names, startup results and child specifications to their declared identity. All three facades use named for trusted attachment. Native raw names are still admitted, without implying a typed service registration.

Registry handles distinguish unique/duplicate modes through ordinary types connected to startup options. Only unique registries form server names. Name helpers take two arguments for nil metadata and three for explicitly typed metadata. Raw lookup results are observations, not durable process/service guarantees.

Use Registry<Mode,N,K,V> and RegistryOption<Mode,N,K,V>. The options connect {:keys, Mode} and {:name, Registry<Mode,N,K,V>} through ordinary invariant type arguments. named asserts those parameters without lookup; start_link validates native configuration and returns the native owner PID or checked startup failure. Only Registry<:unique,...> can form via names. name/2 requires a Nilable value domain because native registration stores nil; name/3 accepts explicit metadata V. Both retain the native two/three-element route tuples, with no runtime wrapper. register returns Result<AnyPid,RegistryOperationError>, retaining the native already_registered tuple and declared RegistryError argument failures. Startup likewise returns expected invalid-configuration failures as values, preserving native failure payloads; unrelated exceptions/exits remain native.

Supervisor/DynamicSupervisor/TaskSupervisor/Application facades retain native strategies, child specifications, restart/shutdown/intensity semantics and explicit startup/operation errors. Successful restarts rerun initialization in a new process; prove the resulting invariant conditionally. No preserved in-memory state, successful recovery, availability, child termination bound or liveness theorem. Per-operation closed-world typing is not a concurrency or ownership system.

Child-start result shapes follow the native supervisor family. otp.StartChild<C> is the static Supervisor result: an ignored child is {:ok, :undefined} and its specification remains registered. otp.DynamicStartChild<C> is the DynamicSupervisor/Task.Supervisor result: :ignore is a separate outcome and successful pairs/triples contain an actual PID. DynamicSupervisor does not retain an ignored child. Both types preserve arbitrary native child-start failure payloads. Supervisor termination returns :ok | {:error, :not_found}; deletion also admits :running and :restarting through SupervisorOperationError. These normal-return contracts do not promise that a supervisor call returns or that a process survives.

Application<Args,State,Phase,PhaseArgs> keeps the native startup pair/triple and phase callbacks. LifecycleState<State> = State | List<Never> includes the empty list supplied by native Application when startup omits state. prep_stop accepts and returns this lifecycle domain; stop accepts it and has the ordinary source default that ignores its argument and returns :ok. A narrow override must still handle the possible omitted-state value. Explicit overrides replace defaults. config_change and its otherwise unused configuration type parameter are excluded with hot code upgrades. No application-wide termination or recovery claim is added.

Task<A> is invariant; native linked/unlinked creation remains distinct. Handles are owner-bound by native checks, not a new linear type. Selected signatures:

Operation Result
await/1,2 Result<A,AwaitError>; default 5000ms. Timeout and observed task exit are separate errors, plus invalid owner/arguments.
yield/1,2 Result<Option<Result<A,ExitReason>>,TaskOperationError>; default 5000ms. Outer Error is an invalid invocation, None means no outcome observed, inner Error is an observed task exit.
shutdown/1,2 Same nested shape; default 5000ms with native brutal-kill option. None means no reply collected after shutdown, not a task still available for normal repeated polling.

Await consumes the normal awaited lifecycle; yield may repeat while pending. Preserve native shutdown/monitor cleanup and race behavior. Do not flatten task failure, pending state and invalid caller into the same absence. Native linked task failure can terminate its owner despite a checked await wrapper; use async_nolink when that is the intended native relationship. No automatic retry, rollback or exactly-once execution. Source: Elixir Task.

AwaitError has TimedOut, Exited(reason: ExitReason), InvalidOwner and InvalidArgument(argument: Term). TaskOperationError has InvalidOwner, InvalidArgument(argument: Term) and OperationExit(operation: Atom, reason: ExitReason). Await uses native yield outcomes to distinguish elapsed waiting from a task exiting with :timeout, and cleans up the monitor like native await on timeout. It consumes the awaited lifecycle without automatically cancelling or unlinking the timed-out task. Yield and shutdown retain native polling and reply collection.

Await/yield and process-backed timed shutdown validate 0..4,294,967,295 or :infinity before invocation on the selected runtime. Out-of-range integers return InvalidArgument before consuming a reply/monitor or starting shutdown. :brutal_kill remains available for shutdown. Native completed-task shutdown ignores its shutdown argument, including an out-of-range Integer, and still checks ownership; preserve that distinction. Native queued replies can bypass the upper-bound check on a waiting path; Gale validates await/yield first for consistent checked errors. Ordinary helper predicates and native adapter contracts expose invalid await/yield timeout branches to proof callers, without inferring progress or monitor ownership.

One invariant opaque Stream<A> covers the supported native representations. from_list is an adapter. map/filter/take/each are lazy; each delegates to Stream.each. run executes the stream. Re-enumeration reruns it; there is no memoization promise. Callback-returned Results are ordinary elements or accumulators, not automatic short circuit/flattening.

run -> Result<:ok,StreamError>, to_list -> Result<List<A>,StreamError> and reduce -> Result<Acc,StreamError>. StreamError covers the selected native File.Error and IO.StreamError boundary. This boundary can also catch those same exception types raised by a callback; do not claim to identify their origin. Foreign stream providers must adapt additional expected failures before exposing the interface. Unrelated exceptions, type violations and exits are not indiscriminately caught.

StreamError has File(FileError), IO(IOStreamError) and Output(operation: Atom, path: String, reason: Term) variants. FileError and IOStreamError preserve the original native exception structs and Term payloads; callbacks can raise those types too. Output identifies an adapter open/write/close failure without attributing an unrelated callback failure to the output operation.

File stream construction remains lazy; opening/read failures occur on execution. stream_bytes validates positive chunk size into Result at construction. stream_lines/stream_bytes provide a bounded subset of File.stream! modes. into_file returns checked input/output errors and retains successful nil. Narrow adapters handle output open/write/close errors with operation/path/reason information; do not broadly catch ErlangError or MatchError around user callbacks. Close acquired resources on completion, early halt and unwinding where the process executes cleanup. No rollback of callbacks/partial writes, durability or unkillable-process guarantee.

Proofs describe completed outputs and justified finite bounds. A positive take count alone does not prove termination of an infinite filtered stream. Exclude general infinite-stream extensional, effect-count and external-source trace proofs.

Invariant native Ets<Name,K,V> stores pair objects with keys at position 1; arbitrary key positions are unsupported. Native set/ordered_set/bag/duplicate_bag and access options do not add a table-kind type parameter. insert(table, {key,value}) returns checked Boolean; insert(table,key,value) is a convenience. lookup returns Result<List<{K,V}>,EtsError>; lookup_all projects values. Missing means Ok([]), not first-object Option. Invalid/deleted/inaccessible tables are checked errors.

ordered_set uses native numeric key equivalence, not strict map identity. Preserve bag multiplicity and duplicate_bag duplicates, with no enumeration-order promise. named is a trusted attachment, not validation of every writer or table configuration. Use one shared typed accessor per resource; no compiler registry of names. A typed closed world still permits concurrent changes/deletion. No unconditional put/get law, ownership, continued access or multi-operation transaction theorem. Exclude arbitrary tuple layouts and match-spec metaprogramming. ETS reference.

PersistentKey<V> is invariant and retains native identity. get/1 returns checked missing failure; get/2 returns V with an eager default; put returns :ok, erase Boolean. Present nil remains a value. named_key is a trusted declaration; all readers/writers must share it. Do not add global get/0 with an invented common type. Reads/writes are effectful observations; a retained value stays immutable but subsequent reads can differ. No disk/VM-restart durability. Native reference.

Files, I/O, logging and operating-system interfaces

Section titled “Files, I/O, logging and operating-system interfaces”

The File facade exposes a bounded native API. read returns Result<Binary,Atom>; read_text validates UTF-8 and adds :invalid_utf8. write accepts Binary, including String by subtyping. write/mkdir_p/rm/rmdir retain Result<nil,Atom>; do not globally replace all wrapper success values with :ok. No bang APIs. Paths remain String: no new path type, charlist/raw-filename interface, implicit normalization or sandbox promise.

ls returns Result<List<String>,Atom> with mandatory native text conversion and validation; unrepresentable names return :invalid_utf8. Use the complete native listing (:file.list_dir_all) so malformed raw names are never silently omitted. Preserve native listing order as unspecified; do not replace malformed bytes. exists? keeps native Boolean behavior, including false on metadata failure. It cannot prove a later read succeeds. File operations do not prove stable contents, atomic replacement, rollback or durability. Path helpers keep native names/semantics; environment-dependent expansion is effectful. Expected invalid path/encoding arguments use checked adapters where native operations can fail within the declared Gale input domain. Path.join_list returns Result<String,:empty_segments>, rejecting only an empty segment list. The pure native join/basename/dirname/extname helpers keep native text behavior. Path.expand returns Result<String,path.PathError> and remains effectful: relative paths and home expansion observe the environment. Its Native(reason: Term) preserves declared File.Error, RuntimeError, ArgumentError, UnicodeConversionError or FunctionClauseError values; InvalidUtf8 rejects non-text native output. On the checked Elixir/OTP runtime, renaming the current directory to a raw non-text filename makes OTP return {:ok, {:error, :warning}}. File.cwd passes that inner tuple to IO.chardata_to_string, whose binary/list clauses reject it with FunctionClauseError. This is a native environment failure for a valid Gale String argument; the wrapper preserves the exception value. The declared exception classes are caught across this native call, without claiming to distinguish their internal causes. Other exceptions propagate. This is not an existence, containment or filesystem-stability guarantee.

IO puts/write return Result<:ok,IOError>; inspect returns Result<A,IOError> with the original value on success. This intentional checked interface changes pipeline usage. Separate String-returning inspect remains available but native foreign Inspect protocol behavior is a trust boundary, not an automatically pure logical function. Ordinary extern raises bindings to IO.puts, IO.write and IO.inspect adapt ErlangError, ArgumentError and UnicodeConversionError. Other exceptions, throws and exits retain native behavior. No new charlist/device surface. IOError.Output(operation: Atom, reason: Term) identifies the failed native operation, without distinguishing formatting from writing failures. Gale wrappers add this context; native IO.inspect owns formatting and returns the original value on normal return, including its default custom-inspector error handling. Its contract preserves that value inside Ok, so callers can use the fact after the executable call. The output operation remains effectful and cannot itself be invoked in a proof expression. Adapting a declared exception preserves failure rather than producing Ok.

Include checked Logger log/2,3 and existing level helpers returning Result<:ok,LoggerError>, using native bare_log through a normal adapter. Arguments are eagerly evaluated String/metadata values; no macro call-site source location or lazy-message promise. Filtering is normal success. Ok does not prove backend delivery, flush or durable storage. No retries or fallback output are added. LoggerError.Native(reason: Term) describes the expected frontend boundary.

Sources: File, IO, Logger.

Environment lookups expose these result types:

Call Result
get_env(name: String) Nilable<String>
get_env<D>(name: String, default: D) String | D
fetch_env(name: String) Result<String,EnvError>

The arity-two interface is an ordinary generic Gale wrapper around get_env/1: return the supplied default only when the native lookup is absent. With String as default the result simplifies to String; with nil/Nilable<String> it is Nilable<String>. Allowing another typed default follows the same ordinary union rule, without a same-arity overload or special inference rule. The selected common environment interfaces retain the approved String/nil behavior.

Missing returns nil/default for get and the missing-variable error for fetch. Empty String is present. Defaults are eager. Preserve OS names/case behavior; no trimming, case folding or configuration parsing.

get_env retains the direct native exceptional boundary for invalid names or environment conversion. Its ordinary valid-name precondition restricts input, and returned text is validated before returning it as String. Invalid input/native encoding failures must raise clearly, never masquerade as nil or invalid String. The precondition does not turn compile/check into a runtime check or prove that external environment encoding is valid. This is the narrow convenience API exception to the checked facade policy preserves the Nilable result. fetch_env is the checked choice for dynamic input, with explicit missing, invalid-name and encoding/native-read errors. No EnvName type or secret compiler helper. Reads remain effectful and may differ between calls. EnvError distinguishes Missing, InvalidName, Encoding and Native failures and retains the requested String name. The valid-name condition excludes NUL and equals signs; an empty lookup name follows native behavior. One ordinary source helper supplies the condition and the checked fetch guard. Its ordinary byte matcher decreases the remaining byte length, so verification can establish valid literal names and reject invalid ones from the source body.

system.schedulers_online returns Integer with a positive-result contract, without a constant or progress guarantee. gale_std.node.self() -> Atom matches Node.self; no distributed operation suite is provided. A returned atom establishes no connectivity/service capability. System reference.

gale_std.system.monotonic_time and system_time use native units at /0 and selected atoms second/millisecond/microsecond/nanosecond at /1. Custom integer unit scales are excluded. Clock results may be negative/equal; wall time may move backwards. Monotonic comparisons apply to the same runtime domain, not arbitrary nodes/restarts. Reads are effectful; no elapsed-time/liveness inference from an arbitrary timestamp.

Date/DateTime/NaiveDateTime retain native struct identities and direct field matching/construction. gale_std.naive_date_time exposes naive operations with native names. DateTime.from_iso8601 returns Result<{DateTime,Integer},Atom>, preserving the original offset beside normalized UTC datetime. That offset is not a named time zone. Date and NaiveDateTime parsers retain their checked result shapes. Current UTC constructors are effectful.

A raw shape with Integer fields/Atom calendar is not a valid calendar value. Every facade operation interpreting raw date data (add, compare, formatting, to_unix) uses checked Result<...,DateError> adaptation for malformed components, invalid precision, unsupported/incompatible calendar capabilities, range and declared native failures. DateError distinguishes invalid input from native operation failure, with operation and reason context. Validate before invoking unsafe operations; optional runtime type checking is insufficient. Foreign calendar/database behavior remains an explicit trusted dependency; arbitrary callbacks do not acquire pure contracts from a shape. Do not impose a factory-only restriction or silently repair invalid fields.

The shared gale_std.date.DateError variants are InvalidInput(operation: Atom, reason: Term) and OperationFailure(operation: Atom, reason: Term). Calendar validation runs before native arithmetic, formatting or comparison. Microsecond values and stored precision are validated independently of optional runtime type checks.

Proofs include structural fields, checked validation facts, Result branches and arithmetic on returned scalar values. Structural equality differs from chronological comparison. Full calendar arithmetic, time-zone/DST and future-rule proofs are excluded. Date, DateTime, NaiveDateTime.

Atom conversion checks existing atoms; it does not create atoms from untrusted text. Binary part remains checked with exact slice/length facts, append preserves bytes, and bit_size is the ordinary modeled observation. The pure binary helpers follow native signed-length slicing: both start and start + length must be between zero and the byte size, inclusive. A negative length selects bytes before start, preserving their order; an invalid range returns Error(:invalid_range). A successful slice has the absolute requested byte length. byte_size agrees with bit_size by the eight-bit byte relation. These guarantees use ordinary source contracts, binary patterns and concatenation.

URI keeps native parse/format/query behavior within the declared input domain. decode_query returns Map<Binary,Binary>, preserving its byte API. Malformed escape/native argument failures are checked as Result<Map<Binary,Binary>,UriError>. encode_query remains String-keyed text input. Raw Uri fields do not prove semantic validity: parse/to_string/native formatting failures within their declared inputs require the same checked UriError boundary. No URL safety, reachability or protocol authorization guarantee. All four retained URI operations return Result: parse yields Uri; to_string and encode_query yield String; decode_query yields Map<Binary,Binary>. UriError has Native(operation: Atom, reason: Term), MalformedEscape(offset: Integer), and Encoding(operation: Atom, reason: Term) variants. Invalid percent escapes are rejected with a zero-based byte offset, a stricter check than native decoding. Valid queries preserve native plus-as-space and repeated-key last-value behavior. parse remains native permissive parsing. Formatting validates UTF-8, including bytes from additional foreign struct fields such as legacy authority.

strong_rand_bytes and hash return checked Result<Binary,CryptoError> values. Algorithms are selected by Atom; invalid/unsupported algorithms return errors. Negative counts are invalid arguments; zero produces empty bytes. Adapt expected native argument/crypto/low-entropy errors at the native operation, including structured native reason forms. Do not rely on rescuing only ArgumentError. Unexpected runtime faults stay outside the boundary. On successful random-byte requests, length equals the requested count; supported hash algorithms have their declared output lengths. No crypto security/randomness quality theorem or deterministic model for entropy reads. Resource exhaustion is not an ordinary recoverable byte-count guarantee. CryptoError has InvalidCount(count: Integer) and Native(operation: Atom, reason: Term) variants. Native ArgumentError and documented badarg/notsup/error/low_entropy atoms or three-element reasons are adapted; unrelated exceptions and resource limits retain native behavior.

API family Interface and behavior
kernel.div, kernel.rem, integer.mod Checked Result; zero divisor is Error. Division truncates toward zero; remainder follows dividend; modulo follows divisor. Preserve exact quotient/remainder relationships.
Float add/subtract/multiply/divide Checked Result. Native arithmetic failure, overflow and division by either zero are errors. Native rounding, subnormal results and underflow to signed zero are successful.
integer.to_float Checked conversion; success may round, excessive magnitude fails. No implicit or guaranteed-exact conversion.
kernel.round/floor/ceil/trunc Accept Integer | Float, return Integer with native behavior.
float.round/floor/ceil One and two arguments; omitted precision is zero. Both return Result<Float, :invalid_precision> with native rounding; accepted precision is 0..15.
integer.pow Integer base and Integer exponent, checked rejection of negative exponent. Exact Integer result when successful.
float.pow Float base and Float exponent; checked native domain/overflow failures. Convert Integer exponents explicitly.
integer.parse Both arities return Result<Option<{Integer, String}>, :invalid_base>; default base 10, permitted range 2..36. None is ordinary parse failure; remainder is preserved.
float.parse Option<{Float, String}>, finite result and preserved remainder.
Whole-string numeric conversion Result on invalid input/configuration, including string.to_integer with explicit base.

gale_std.kernel.abs/min/max preserve the numeric input kind. abs exposes Integer magnitude laws and Float kind/transport facts without a numerical Float theorem. min/max require one common numeric kind through an ordinary finite generic constraint. No compiler rule recognizes these library names. Integer parity/clamp helpers retain their declared interfaces; invalid bounds/counts/bases follow the operation’s checked or explicit-contract domain.

gale_req keeps high-level native requests with typed Json input and binary response bodies. RequestError preserves native failures or tagged option/output context. An explicit json option encodes null and false as JSON scalars. Reject duplicate options, body/form/json conflicts, negative counts and invalid waits before invoking a Plug; waits use 0..4,294,967,295 or :infinity. Preserve user Plug exceptions, throws and exits. Header/trailer text is validated; the original Req.Response remains intact. Network, retries and response contents have no proof guarantee. See the package reference.

gale_decimal requires Decimal 3.1.2 or a later 3.x release and keeps the original finite native Decimal struct. Raw fields do not establish sign/coefficient validity: semantic operations validate inputs in every build and return Result<...,DecimalFailure>. InvalidInput carries the operation, argument and raw value; Native preserves DecimalError or ArgumentError; NonFinite preserves a rejected native result, including either div_rem component. round/2 keeps native half_up behavior. Context-dependent arithmetic proofs are excluded. See the package reference.

Gale test modules end in _test and expose zero-argument pub functions for ExUnit. Use gale_std.test runtime assertions; proof assert blocks also run when runtime checks are enabled. Runtime checks may be enabled in any environment and raise on representation mismatches, false executable contracts and opaque invariants. They do not validate phantom or mailbox identity. Foreign code must honor declared interfaces; explicit decode is the untrusted-data route.

Generated sidecars carry readable native calls and typed specs. Internal native protocol use is a trusted adapter boundary, not a Gale protocol feature. Full native library surfaces, ownership, temporal/crypto/calendar/Unicode proofs and hot upgrades are excluded according to the language guide. Req and Decimal have separate package interfaces and expected failure adapters.

string.length returns a nonnegative native grapheme count, zero exactly when the String is empty. Byte concatenation guarantees do not imply additive grapheme counts; combining characters can join across the boundary.

String prefix, suffix and substring observations describe exact UTF-8 bytes. string.starts_with?(text, prefix) holds exactly when some String remainder satisfies text == prefix <> remainder; ends_with? uses the corresponding leading remainder. contains? holds exactly when text decomposes into a leading String, the substring, and a trailing String. Empty patterns match. These native contracts perform no Unicode normalization or grapheme comparison.

gale_inertia.page combines schema-backed fields with a backend props type, component identity and delivery policies. page.render encodes eager fields before rendering and returns validation issues. Deferred encoding failures raise GaleInertia.EncodingError with the field path. Getters preserve native failure behavior and only run when their delivery policy selects them.

mix gale_inertia.typescript generates PageProps and PartialPageProps from the same page factories. Shared fields are declared in each page. Optional and deferred props are optional on initial visits; partial response types make all fields optional. Typed rendering disables camelization and reserves errors for the native adapter. See libs/gale_phoenix/example for request decoding, typed page rendering and frontend consumption.

For standalone schemas, gale_schema.typescript.emit describes accepted input, while emit_output describes encoded output. Defaulted fields are required in output. emit_many(descriptions, Direction.Output) supports heterogeneous roots. Every TypeScript entry point checks definition names and conflicts; unsupported transforms and opaque codecs fail generation. Named lazy occurrences can refer to an active definition; concrete nested definitions cannot reuse that active name. mix gale_schema.typescript --check and mix gale_inertia.typescript --check detect stale files without writing. gale_std.json.to_native implements closed JSON conversion in Gale for native APIs.