§7.4 The runtime library
Every emitted project ships the runtime as one module per concern under
out/__bynk_runtime/ (result, bytes, equality, int, errors, storage,
boundary, http, queue, agent, auth, connection, messages, locale,
wasm), generated by bynk. The per-context and per-test modules import each
shared value or type from the module that defines it — at
./__bynk_runtime/<module>.js for a top-level module, or
../__bynk_runtime/<module>.js repeated by directory depth. A project emits
exactly the modules its emitted files import, closed over the modules’ own
imports (a type-only import counts); a project that imports none emits none.
The directory name begins with _, which no Bynk identifier or source path
component can, so it cannot collide with a user file. This section is the
normative contract: a conforming implementation MUST provide these exports
with these shapes and semantics, from the module named here. Each module is
headed // Generated by bynk — do not edit by hand. and is identical across
projects that emit it. Hand-written adapter bindings may still import from
./runtime.js; the compiler rewrites that import to the defining modules.
The TypeScript blocks here are the contract, not examples; the dynamic meaning of the constructs in §7.3 is defined against them.
§7.4.1 Result and Option
Section titled “§7.4.1 Result and Option”Both are discriminated unions over a tag field — the same shape user sum types
lower to (§7.3.1). Ok, Err, and Some are
constructor functions; None is a constant.
export type Result<T, E> = | { readonly tag: "Ok"; readonly value: T } | { readonly tag: "Err"; readonly error: E };
export type Option<T> = | { readonly tag: "Some"; readonly value: T } | { readonly tag: "None" };Ok/Err are shared with HttpResult (§7.4.3); a Bynk
match discriminates them on tag and the ? operator
(§7.3.2) inspects tag === "Err".
§7.4.2 ValidationError
Section titled “§7.4.2 ValidationError”The error a refined or opaque .of constructor
(§6.4) returns as the Err side of
its Result:
export interface ValidationError { readonly field: string; readonly message: string; readonly value: unknown;}§7.4.3 HttpResult
Section titled “§7.4.3 HttpResult”The built-in HTTP-result sum (§5.7), a
tag-discriminated union with a constructor namespace. Its variants track the
common, modern HTTP status codes (RFC 9110) — success (Ok, Created,
Accepted, NoContent), redirection carrying a Location URL (Found,
SeeOther, PermanentRedirect, …), and the client/server failures
(BadRequest, NotFound, TooManyRequests, ServerError, …). Four 200-only
variants carry a body that bypasses JSON serialisation: Streaming (an
SSE-framed Stream[String]), Raw (a Bytes body written under an
author-declared content-type, with serialiseValue bypassed entirely — no
codec runs), RawTagged (a Raw body plus the entity tag sent as its
ETag), and RawStreamed (#2623: a Stream[Bytes] body written chunk by chunk
as it is pulled, with no ETag whatever opts.weakEtag says, since its bytes
can’t be hashed without buffering them). RawCreated writes a Raw body at 201, with no ETag whatever
opts.weakEtag says, and RawError one at an author-chosen 4xx/5xx status. See
the HTTP reference for the full table.
The runtime maps each variant to an HTTP response:
| Export | Role |
|---|---|
HttpResult<T> | the result type, and HttpResult the constructor namespace |
httpResultToResponse(result, serialiseValue, opts?) | maps a variant to a Response with the corresponding status (Ok → 200, Created → 201, NoContent → 204, BadRequest → 400, … ServerError → 500); with opts.weakEtag, an Ok response, or a Raw body of at most 1 MiB, also carries a weak ETag (see below); a RawTagged response always carries its own tag, and throws if the tag is not an RFC 9110 entity tag |
matchPath(pattern, path) | matches a route pattern such as /orders/:id, returning the captured parameters or null |
headResponse(response) | rebuilds a GET response as its HEAD answer — same status and headers, empty body — without reading (and so without draining) the original body |
weakETag(body) | a weak validator W/"…" over a serialised body, from a synchronous non-cryptographic hash (FNV-1a); a Raw body is hashed the same way over its octets |
applyCache(response, maxAgeSecs, scope, immutable?) | stamps Cache-Control: <scope>, max-age=<n> onto a response, in place, appending , immutable when immutable is true |
notModifiedIfMatch(response, request) | when the response carries an ETag and the request’s If-None-Match matches, returns a 304 with an empty body copying the ETag + Cache-Control; otherwise returns the response unchanged |
applySecurityHeaders(response, policy) | stamps the service’s security headers onto a response, in place — X-Content-Type-Options: nosniff when policy.nosniff, and Strict-Transport-Security: max-age=<n> when policy.hstsMaxAgeSecs is set |
The entry router (§7 emission) answers the RFC 9110 method contract derived
from the declared routes, around the HttpResult lowering above: a request to
a live path under an undeclared method is a synthesised 405 carrying an
Allow header (the union of the path’s methods, plus HEAD where GET exists,
plus OPTIONS); a plain (non-preflight) OPTIONS is a 204 carrying
Allow; and a HEAD to a GET route runs the GET handler and returns its
status and headers with an empty body (via headResponse). A path that exists
under no method is still 404. These are synthesised router responses (like
the CORS preflight and the 404) and do not touch the HttpResult sum — the
author-returnable MethodNotAllowed variant is a distinct, deliberate deny.
HEAD/OPTIONS are not author-declarable methods.
The entry router also lowers conditional caching (v0.140) around the same
GET responses. Every GET invokes httpResultToResponse with weakEtag, which
derives a weak ETag for an eligible response — the JSON Ok variant over its
serialised body, or a Raw body of at most 1 MiB (1,048,576 bytes) over its
octets — while a RawTagged response carries its handler-supplied tag; notModifiedIfMatch then compares the
request’s If-None-Match and, on a match, replaces the 200 with a synthesised
304 (empty body, the ETag and any Cache-Control copied across). A
handler carrying an @cache annotation (§5.7.2)
additionally has applyCache stamp Cache-Control: <scope>, max-age=<n> (with
, immutable appended for immutable: true). A malformed RawTagged tag throws
inside the dispatch, so the route answers the entry’s fault 500 and logs the
route, never a malformed header. The
composition order is normative:
applySecurityHeaders(applyCors(notModifiedIfMatch(applyCache(…), request), …), …)
— the conditional check runs after the handler (the body must exist to hash),
the CORS stamp runs around it, and the security-header stamp
(§5.7.3) runs outermost, so a
cross-origin 304 still carries both Access-Control-Allow-Origin and
X-Content-Type-Options. The CORS and security header sets are disjoint, so their
relative order is not observable. The 304, like the 405/preflight, is a
synthesised router response and does not touch the HttpResult sum;
Streaming, a Raw body over 1 MiB, redirect, and error variants carry no ETag
and are never answered 304. Non-GET responses carry the CORS and security headers but are
otherwise byte-for-byte unchanged.
Security headers (v0.141) are stamped on every from http response, not
only opt-in ones: the compiler synthesises a default policy (nosniff: true, no
HSTS) for every from http service, and applySecurityHeaders stamps
X-Content-Type-Options: nosniff unless the service declares security { nosniff: false }. A security { hsts: <Duration> } additionally stamps
Strict-Transport-Security. The stamp applies uniformly across the HttpResult
variants and the synthesised preflight, 405/OPTIONS, and 304.
Content-Security-Policy and X-Frame-Options are never emitted (the surface
serves bytes, not markup).
Request body limits (v0.142) are enforced differently from the header
policies above: they are a request-side check, not a response-stamping helper.
For a body-taking route (POST/PUT/PATCH) with an effective cap
(§5.7.4), the entry router compares the
request’s Content-Length against the cap inline in the route dispatch —
there is no applyLimit runtime helper analogous to applyCors/
applySecurityHeaders. When Content-Length exceeds the cap the router
synthesises a 413 PayloadTooLarge ({ kind: "PayloadTooLarge", details: … },
reusing the existing 413 status — the HttpResult sum is untouched) and returns
it before the body is read and before the by/Bearer auth seam, the boundary
posture of the 405. That synthesised 413 is then passed through the same
applyCors/applySecurityHeaders stamping as every other response, so a
cross-origin caller can read it. A route with no effective cap runs the body read
unchanged. Because that check keys on Content-Length (which may be absent for a
chunked transfer, or wrong), the body of a capped route is then read through the
runtime’s counting reader (readCapped): the bytes actually read are counted and
the read is cancelled, with the same 413, once it crosses the cap. A route
declared @raw(contentType:) first has its Content-Type matched by
mediaTypeMatches (parameters stripped, case-insensitive; */* matches all), and
a mismatch is a synthesised 415 UnsupportedMediaType ({ kind: "UnsupportedMediaType", details: … }), stamped and ordered like the 413. Its
body is then the counted octets as a Uint8Array, with no decode. A route declared
@form has its Content-Type matched by formMediaTypeMatches (the media type
application/x-www-form-urlencoded, parameters stripped, case-insensitive, and a
charset parameter, when present, UTF-8), a mismatch being the same 415; its body is
read as UTF-8 text and decoded by formObject, which reads the URL-standard key/value
pairs into the record’s JSON form by the rules of the static semantics.
QueueResult (v0.44) is the analogous built-in for the queue protocol: a
non-generic tag-discriminated sum with a constructor namespace, variants Ack
(confirm the message) and Retry (redeliver, carrying a String reason). A
queue handler returns Effect[QueueResult]; the runtime routes Ack →
msg.ack() and Retry → log the reason + msg.retry().
| Export | Role |
|---|---|
QueueResult | the verdict type and its Ack / Retry(reason) constructor namespace |
EmailVerdict (#3328) is the verdict of the email protocol, by the same agency
rule, but declared in bynk.cloudflare as an ordinary sum rather than built in:
Accept, Reject(reason: String), Forward(to: String) and Reply(message: EmailReply). It travels with InboundEmail (the message, whose from is a
claim), EmailReply (the content of a reply; the runtime fills in From, To
and the threading headers), InboundAttachment, DmarcVerdict (DmarcPass,
DmarcFail, DmarcNone) and SenderIdentity (address and dmarc, the
identity of the Sender actor). The Worker mapping that produces and acts on
them is a later slice.
§7.4.3a Composite keys
Section titled “§7.4.3a Composite keys”(constrained-generics slice 2, #2684) A value Map or Set whose key type is a
Key type other than a primitive holds its keys under a canonical encoding.
This is internal to the runtime and not part of the published ABI.
- A collection whose keys are all primitive (
string,number,boolean) is a plainMap/Set, and every site that is statically primitive-keyed emits what it always did. - A collection that meets its first composite key is promoted to a subclass of
Map/Setthat keeps the original keys, so iteration returns real keys, in insertion order, and indexes them by__bynkKeyEncode(k). __bynkKeyEncode(v)isJSON.stringifyof a canonical tree: strings, numbers and booleans as themselves, aUint8Arrayas its lowercase hex string, an array element-wise, any other object as its own keys sorted, each mapped recursively. For two values of oneKeytype the encodings are equal exactly when the values are==(injectivity);-0and0encode alike, and aFloatnever reaches the encoder. A sum’stagtakes part, so payloads of different variants never collide.__bynkEqcompares the subclasses structurally throughhas/get.- The set decoder rejects a repeated member by value. The map decoder likewise
rejects an entry whose decoded key equals an earlier one, as
StructuralMismatch(“a distinct map key”) at$[i][0]; the comparison is on the canonical key, soDecimal1.20and1.2collide.
serialiseAgentKey (§7.4.4) is a separate function and unchanged: it addresses
stored durable objects.
§7.4.4 Agent state
Section titled “§7.4.4 Agent state”Agent classes consume a Durable-Object-shaped state surface. In bundle mode and
under bynk test this is backed in memory; in workers mode it is a real
Durable Object (§7.3.3).
| Export | Role |
|---|---|
DurableObjectStorage, DurableObjectState | the storage and state interfaces an agent class consumes |
KVNamespace | the Worker KV namespace shape the bynk.cloudflare binding consumes — get/put (with expirationTtl options, v0.23)/delete/list (the cursor-page shape the drain follows) |
InMemoryStorage | an in-memory DurableObjectStorage, used in bundle mode and tests |
makeTestState(name) | builds an in-memory DurableObjectState |
serialiseAgentKey(value) | serialises an agent key to a stable string — semantically-equal keys (records compared by sorted fields) MUST serialise identically |
StateRegistry<K> | a serialised-key-to-state map with getOrCreate(key) and reset(); reset() clears all state so a fresh test sees a clean slate |
DurableObjectStub, DurableObjectNamespace | a minimal structural view of the Cloudflare Durable Object surface |
callDurableObjectMethod(stub, method, args, deps) | routes a workers-mode agent method call through the stub under the /_bynk/agent/<method> protocol; args arrive encoded and the result returns as raw JSON |
AgentWire, WireCodec, AGENT_WIRE_PASS | an agent’s wire table: a boundary codec pair (enc/dec) per handler parameter and result, and the pass-through codec for a position with no wire form (#1678) |
decodeAgentArgs(wire, method, args), encodeAgentResult(wire, method, result) | the Durable Object side of the wire: decode a call’s arguments (throwing a boundary error on failure, an internal fault) and encode its result |
makeWorkersAgent(binding, key, wire?) | a typed proxy over a Durable Object stub; with a wire table it encodes each call’s arguments and decodes its result |
makeAgent(registry, binding, key, constructBundle, wire?) | the single construction helper: a present binding selects the workers path (passing wire to the proxy), an absent one the bundle registry path, so call sites are identical across targets |
makeIntegrationDoNamespace(construct) | an in-process Durable-Object namespace for cross-context system-tier tests |
§7.4.5 The cross-Worker boundary protocol
Section titled “§7.4.5 The cross-Worker boundary protocol”On the workers target a cross-context call is JSON over a Service Binding,
validated at the boundary (§6.5).
export type JsonValue = | null | boolean | number | string | JsonValue[] | { [k: string]: JsonValue };
export type BoundaryError = | { readonly kind: "MalformedJson"; readonly details: string } | { readonly kind: "StructuralMismatch"; readonly path: string; readonly expected: string; readonly actual: string } | { readonly kind: "RefinementViolation"; readonly path: string; readonly violation: ValidationError } | { readonly kind: "Transport"; readonly status: number; readonly details: string };| Export | Role |
|---|---|
ServiceBinding | the fetch-shaped binding a consumer calls |
callService(binding, servicePath, argsJson, deserialiseResult, callerContext, contractHash, env, calleeContext) | issues the call to /_bynk/call/<servicePath>, decodes the response, and raises a BoundaryError on transport or shape failure. v0.54: callerContext (the calling context’s qualified name) is stamped into the X-Bynk-Caller header so the callee’s by c: Caller handler reads a live CallerId; the args body is unchanged. v0.177: contractHash is stamped into X-Bynk-Contract. #1971: the request is signed under the key for the edge to calleeContext (BYNK_CALL_TO_<CALLEE>, read from the calling Worker’s env), sending X-Bynk-Timestamp and X-Bynk-Signature; with the key unset the call throws before it is sent. #1969: the request is a POST stating X-Bynk-Wire: 1, the wire format version it speaks |
verifyCall(request, env, callee) | #1971: the request’s body as text when it is signed for callee by a caller this Worker holds a key for (BYNK_CALL_FROM_<CALLER>), within the timestamp window; otherwise the refusal to return: 413 for a body over 1 MiB, 401 for anything else. Fails closed when the Worker holds no key for the caller. The first step of every /_bynk/call/ and /_bynk/event/ dispatch |
boundaryError(error) | wraps a call error (a BoundaryError, ContractMismatch or CalleeFaulted) as a throwable Error |
faultResponse(context, route) | #2193: the 500 a Worker entry answers when a handler faults. A fault in an on call service (route is call <service>) carries X-Bynk-Fault: <context>, which callService raises as CalleeFaulted { context, service, status } |
Dev-only inspection (#3581)
Section titled “Dev-only inspection (#3581)”A build made by bynk dev adds a runtime module, inspect, that a deploy build
does not emit (the module is emitted only when emitted code imports it). It
holds: noteAgentInstance, which an agent factory hands its agent through to
record the instance’s {class, key, id} in the Worker’s BynkInspectRegistry
Durable Object; inspectAgent, which an agent’s fetch answers /_bynk/inspect
with; and inspectRoute, the Worker’s /_bynk/inspect/ route.
The route is signed as an internal call is (verifyCall), by the reserved caller
bynk.dev under the local key, and is refused with a bare 401 otherwise. It is a
POST with no body, because the call signature covers the method. A read applies
checkStoredLayout and checkStoredSchemaVersion to the raw stored record and
returns it; it does not run loadState (which upgrades an older layout by writing),
commit, or migrate. A deploy build has neither the route nor the registry, and its
output is byte-identical to a build without the feature. The history of
transitions is stored under the reserved key __bynk_dev/history, outside every
layout-2 key namespace: a ring buffer of the last 50 committed transitions, each
{handler, old, new, at}, appended by commitState in a dev build only. old
and new carry the Cell fields in wire form and each collection’s size, not its
entries, and old is null for a first commit. A refused transition is not
committed and so is not recorded. A migration commit records handler: null.
The buffer is one stored value, so it is trimmed by size as well as by count
(HISTORY_BYTES, 96 KiB, under Durable Object storage’s 128 KiB cap on a value).
§7.4.6 Non-exports: brands and Effect
Section titled “§7.4.6 Non-exports: brands and Effect”Two parts of the surface have no runtime export, by design:
- Brands are compile-time TypeScript intersections, erased after type-checking (§7.3.1); the runtime library carries no brand values.
Effectis realised asPromise(§7.3.2); there is noEffectruntime value.Effect.purelowers away at emission and<-lowers toawait, so neither needs runtime support.
§7.4.7 Prelude actors (v0.45)
Section titled “§7.4.7 Prelude actors (v0.45)”The compiler provides four prelude actors — boundary contracts available
without a declaration: Visitor (auth = None; identity ()), and the
Internal actors Scheduler, Producer, and Caller that back the
per-protocol defaults (cron, queue, and on call respectively). Caller yields
the calling-context identity; the other prelude actors carry no identity payload
(()) in this increment. Prelude actors have no runtime export — like
brands, an actor is a compile-time contract; the zero-crypto schemes mint no
runtime verification code (see §7.3).
§7.4.8 Authenticated-scheme verifiers (v0.47, v0.51, v0.151)
Section titled “§7.4.8 Authenticated-scheme verifiers (v0.47, v0.51, v0.151)”The authenticated schemes do export runtime verification helpers, emitted into the per-Worker runtime module and called from the boundary seam (§7.3.4a):
verifyBearerJwtHs256(Bearer, v0.47) — HS256-verifies a JWT with WebCrypto (crypto.subtle.verify, constant-time), rejects anyalg ≠ HS256, enforcesexp/nbf(rejecting malformed NumericDate claims), and returns thesubclaim — plus, since v0.53, the full verifiedclaimsobject for refinement-actor authorisation — on success; any failure is reported so the seam maps it to a 401. The authorisation predicate of a refinement actor is lowered inline over those claims (no new runtime export), a failed invariant mapping to 403.verifySignatureHmacSha256(Signature, v0.51) — recomputes HMAC-SHA256 over the raw request body (or<timestamp>.<body>when a timestamp is bound) with the sourced secret and constant-time-compares (crypto.subtle.verify) against the configured signature header, accepting a bare hex digest or asha256=<hex>prefix. When a timestamp is configured it MUST be a finite number withintoleranceseconds of now; a malformed hex signature, an absent header, or a stale/non-numeric timestamp returnsfalse. Returns a boolean — the seam mapsfalseto a 401.verifyOidcJwt(Oidc, v0.151) — verifies an asymmetrically-signed (RS256/ES256) JWT against a provider’s published JWKS. It fetches the key set (cached ~10 min, refetched on akidmiss so key rotation heals without a redeploy — thekid-miss refetch rate-limited by a ~30 s cooldown so an attacker-chosen novelkidcannot amplify into fetches; a bad signature against a published key never refetches), imports the matching signing key (use: "sig") and verifies the signature with WebCrypto (crypto.subtle.verify), rejectingalg: noneand symmetricHS*algorithms (algorithm-confusion). It then enforces the trust contract —issequals the declared issuer,audcontains the declared audience,expis present and in the future,nbf(if present) has passed (both with a small clock-skew leeway) — and returns thesubclaim (plus the full verifiedclaims) on success; any failure is reported so the seam maps it to a 401. It takes no secret: the trust root is the provider’s public JWKS URL.
verifyBearerJwtHs256/verifySignatureHmacSha256 source their secret from env
(the same channel the Secrets capability reads); the secret is used only inside
the verifier and never logged. verifyOidcJwt sources no secret — it fetches the
provider’s public keys over the network.
§7.4.9 Streams and connections (v0.100, v0.102+)
Section titled “§7.4.9 Streams and connections (v0.100, v0.102+)”A Stream[T] lowers to a host AsyncIterable<T> emitted inline
(§7.3.10), so
stream code needs no runtime import. A streamed HTTP response is a standard
Response whose body pulls the stream lazily: encoded as Server-Sent Events for
Streaming, written chunk by chunk for RawStreamed. Building the response
claims the stream, as the inline ops do, through the exported
claimStream(stream), which throws bynk: a stream can be read only once on a
stream already read. A HEAD answered from a streamed GET cancels the body
unread, which returns the stream’s iterator. A throw from the stream mid-body
errors the response body.
A Connection[F] is lowered against a runtime Connection<F> interface
with send(frame: F): void (JSON-encodes and writes a frame) and close(): void
(ends the socket). Two implementations satisfy it:
TestConnection<F>(bundle/test) — a capture-and-inspect channel exposingsent: F[](the frames written to it) andclosed: boolean, so a WebSocket service is fully testable under Node with no Durable Object.- the Workers binding — wraps a hibernatable Durable-Object WebSocket; a stored
connection survives hibernation (re-associated via the platform’s
serializeAttachment/getWebSockets) and is restored on rehydration, a platform-supplied guarantee the language relies on but does not implement.
Held connections are never serialised into the durable state record; on Workers a
Map[K, Connection] lives in an in-memory side-table keyed alongside the durable
state.
§7.4.10 Generative properties and contracts (v0.114, v0.115)
Section titled “§7.4.10 Generative properties and contracts (v0.114, v0.115)”A generative property has no runtime-library export: like the expectation
helpers, the generator, the seeded PRNG, the case loop, and the shrinker are
emitted into the per-test module that declares a property (never into the
deployable). This section is informative — it fixes the runtime contract the
emission satisfies, not an exported API.
- Root seed. Each run resolves one root seed: the hex value of
BYNK_TEST_SEEDif set (threaded bybynk test --seed <hex>), otherwise a fresh random 32-bit value. Every property derives its own generation seed deterministically from the root seed and a stable per-property ordinal, so a run is fully determined by its root seed. - Generator. Each
for all x: Tbinding carries a generator overT’s refinement domain (§5.9a): boundary values are drawn first (the refinement floor/ceiling, minimum-length strings, each sum variant), then random inhabitants. Generated subjects are branded to their type — an opaque value through its.unsafeconstructor, a refined value through an inline brand cast (ADR 0182) — so a generated subject is valid by construction. - Case loop. The runner draws up to a bounded number of accepted cases per
property; a
wherefilter that rejects a tuple skips it without consuming a case. The body is the property’sexpects, which throw anExpectationErroron failure exactly as acasebody does. - Shrinking. On a counterexample the runner minimises each input toward its
boundary (integers toward the refinement floor, strings toward minimum length,
sums toward the first variant) while the predicate still fails, then reports the
case count, the root seed, the shrunk tuple, and a copy-paste
--seedreproduce line — reusing the expected-vs-actual renderer for the failingexpect. The report rides the existing runnermessagefield; the pinned--format jsonshape is unchanged.
Contract runner attack (v0.115)
Section titled “Contract runner attack (v0.115)”A contracted pure function reachable from a test target is attacked by the
same generative runtime (ADR 0150): the runner draws arguments over the
parameters’ refinement domains, filters them by the conjunction of the function’s
requires (exactly as a where filters — a rejected tuple skips without
consuming a case), and calls the function. The dev/test call-site guard
(§7.3.5b) asserts each
ensures and throws on violation; the runner treats the guard’s contract error
as a shrinkable failure, so a broken ensures reports a case count, the root
seed, and a shrunk counterexample with a --seed reproduce line — identical in
shape to a property failure. The attack is emitted per module alongside the
guard (dev/test only), never in the release build. Int arguments are coerced to
number at the call (generation produces bigint; functions do number
arithmetic).
§7.4.11 The observation recorder (v0.117)
Section titled “§7.4.11 The observation recorder (v0.117)”A case that observes a capability (ADR 0152) records its calls through a
recording proxy emitted into the test module, dev/test build only. The proxy
wraps the case’s deps object: for each observed capability operation, the seam
function is replaced by a wrapper that appends the call to a per-operation log and
then delegates to whatever stands behind the seam, returning its result unchanged.
function __bynkRecordDeps(deps: any, spec: Record<string, string[]>, obs: { log: Record<string, { args: any[]; order: number }[]>; n: number }): any { for (const cap of Object.keys(spec)) { if (!deps || !deps[cap]) continue; for (const op of spec[cap]) { const orig = deps[cap][op]; if (typeof orig !== "function") continue; const key = cap + "." + op; obs.log[key] = obs.log[key] ?? []; deps[cap][op] = (...args: any[]) => { obs.log[key].push({ args, order: obs.n++ }); return orig.apply(deps[cap], args); }; } } return deps;}The contract: record-then-delegate, so the arguments are logged as passed and
the delegated return is untouched; the order index is monotonic across all
operations, so A.op before B.op is a comparison of the first recorded orders; and
the log is per-case (a fresh __obs per case), so counts are scoped to the case.
The sugar and trace(Cap.op) are two views of this one log — they cannot disagree.
The proxy is emitted only under bynk test; the deploy build carries none of it.
§7.4.12 The stub clause (v0.118)
Section titled “§7.4.12 The stub clause (v0.118)”A stub clause (ADR 0154) lowers to a stub that stands behind a capability
seam in place of the real provider, emitted into the test module, dev/test build
only. It sits behind the recording proxy (§7.4.11), so a case can both stub a
return and observe the call at one seam.
For a stubbed operation, the clauses for that method form an ordered match
table: each recorded call is tried against the argument patterns top to bottom
and the first match wins (a _ pattern matches anything; a literal / value
pattern compares by equality). The matched clause yields the operation’s result:
- a
returns <value>clause yields the constant value; - a
failsclause raises a capability fault: the operation throws, taking the same path a real provider’s failure takes. The fault is untyped, never anErr: it propagates out of the handler and out of the case, failing it, unless the case claims it withexpect <call> faults(§7.4.12a). It is distinct from an in-bandResult, which areturns Err(…)clause stubs and a case asserts directly; - a
returns each [<outcome>, …]clause is backed by a per-call cursor: the stub holds an index that advances on each call, servingoutcomes[min(i, n-1)]— so the last outcome repeats once the sequence is exhausted (steady state) and an extra call never spuriously fails the case. Each outcome is a value, afailsfault, orok(v).
The contract: match-then-serve, deterministic and side-effect-free apart from
the sequence cursor’s advance; a stub is scoped to its case (a suite-scoped
stub state is instantiated fresh per case), so a cursor never carries state between
cases, and precedence (case > suite > tier default) is resolved at emission, not at
run time. The stub is emitted only under bynk test; the deploy build carries none
of it.
§7.4.12a The fault claim
Section titled “§7.4.12a The fault claim”A fault claim, expect <call> faults
(§5.9e), awaits the call and
holds when it throws. The contract:
- any thrown value is a fault: an injected
fails, a real provider’s failure, an invariant violation. A fault is untyped, so the claim does not discriminate between them; - the case’s own expectation failure is not a fault. A failed
expectraised while the call is evaluated propagates and fails the case, as it would anywhere else; - a call that returns fails the claim, reported as
expect <call> faultswith the notethe call returned without faulting; the returned value is discarded.
The claim runs only in-process, at unit and integration. At system a fault
reaches the harness as the deployed Worker’s error response, which the claim
cannot observe (bynk.test.faults_needs_in_process). The fault’s 500 carries
no error payload, so the driver decodes it as ServerError(""); a handler’s
deliberate ServerError(m) decodes as ServerError(m). An empty message is the
only difference, and ServerError("") is itself a legal return, so it does not
reliably tell the two apart: by design (#1811), a system case observes
responses, not faults.
§7.4.12b The snapshot claim
Section titled “§7.4.12b The snapshot claim”A snapshot claim, expect <value> matches snapshot "<name>"
(§5.9f), compares the value with
a stored snapshot. The contract:
- Encoding. The value is encoded as
Json.encodeencodes it, then parsed back and printed with the keys of every object sorted and an indent of two spaces. The snapshot is that text; two values are equal when their texts are. - Storage. A suite file’s snapshots are one JSON object in
snapshots/<suite file without .bynk>.snap.jsonunder the project root, keyed by case name and then snapshot name, printed the same way and ending in a newline. - Inlining. The build reads the project’s
snapshots/folder and inlines each suite file’s text into its test module. The harness reads no file at test time. - Comparison. A claim passes when the stored text equals the value’s. It fails when they differ, reporting a line diff, and when no snapshot is stored for the case and name, so a missing snapshot is never a pass.
- Recording. Under
bynk test --update-snapshotsa claim records its value instead and passes. The runner reports, per snapshot file, the counts of snapshots written (no stored value), updated (a different one) and obsolete (stored for a case and name the suite no longer takes), and the file’s new text. Only the driver writes: it writes that text, deletes a file that becomes empty, and deletes asnapshots/file no suite takes a snapshot into. Obsolete snapshots are decided from the suite’s source, not from the cases that ran, so a run filtered by--caseor--suiteneither loses nor reports the snapshots of the cases it skipped. - Reporting. Every output format carries the three counts: a
snapshotsobject on the JSON document and on the NDJSONrun-end, and a summary line in therichoutput; none for a project that takes no snapshot.
§7.4.13 The par join (#2640)
Section titled “§7.4.13 The par join (#2640)”__bynkSettleAll(thunks) is the runtime half of a par block (§4.8.7b). thunks is
the tuple of functions the block compiled, one per binding in source order, each
returning the effect’s promise (or value); the result is the tuple of their values,
in the same order.
export async function __bynkSettleAll<const T extends readonly (() => unknown)[]>( thunks: T,): Promise<{ -readonly [P in keyof T]: Awaited<ReturnType<T[P]>> }>;The contract: it calls every thunk, in order, before awaiting any, so each effect
is issued before the next binding is evaluated. A thunk that throws synchronously is
a rejected entry; later thunks are still called. It then waits for every entry to
settle (Promise.allSettled), so nothing the block started is running when it
returns or throws. If none rejected it returns the values. If any rejected it throws
the first rejection in input order — not the first in time — and attaches the
later reasons to it as a suppressed array, in input order, when the first is an
object. Callers are the par block and, since #2662, the parTraverse, parTraverseAll and parTraverseTry lowerings (list and query/broadcast receivers), which pass xs.map((x) => () => f(x)); the result is then an array of the awaited values, in input order. The helper is codegen, not part of the published emit ABI (ADR 0310): it
lives in the settle runtime module, which a project emits only when a module
imports it.
§7.4.14 The within race (#2683)
Section titled “§7.4.14 The within race (#2683)”__bynkWithin(promise, ms, exec) is the runtime half of e.within(d) (§5.5). promise
is the effect, ms the deadline in milliseconds, and exec the handler’s execution
context (deps.__exec).
export async function __bynkWithin<T>( promise: Promise<T>, ms: number, exec: { waitUntil(promise: Promise<unknown>): void },): Promise<Result<T, { readonly after: number }>>;The contract: it races promise against setTimeout(ms). If the promise settles first
it clears the timer and yields Ok(value), or rejects with the promise’s own reason. If
the timer fires first it yields Err({ after: ms }) and calls exec.waitUntil(promise)
with the promise itself: the effect is neither cancelled nor wrapped, so it runs to
completion and a fault in it after that point is the platform’s to report, not the
caller’s. A tie goes to the promise. A deadline that is not over zero and at most
2,147,483,647 ms hands the promise to waitUntil and then throws, so the effect
already running is not left unseen. The helper reads exec.timers (set(fn, ms) and
clear(handle)) in place of setTimeout when it is present: the test harness supplies
virtual time that way, and no emitted handler does. Like __bynkSettleAll, it is
codegen, not part of the published emit ABI (ADR 0310), and lives in the settle
runtime module.
§7.4.15 The race helper (#2711)
Section titled “§7.4.15 The race helper (#2711)”__bynkRace(promises, exec) is the runtime half of a.race(b) (§5.5). promises are
the effects in source order, and exec the handler’s execution context
(deps.__exec).
export function __bynkRace<T>( promises: readonly Promise<T>[], exec: { waitUntil(promise: Promise<unknown>): void },): Promise<T>;The contract: it resolves with the first promise to fulfil. A tie, where promises
settle in the same turn, goes to the earlier in promises, because each is subscribed
in that order. A rejection does not decide the race while another promise may still
fulfil. Once a promise has won, every other promise is handed to exec.waitUntil as
itself: it is neither cancelled nor wrapped, so it runs to completion, and a fault in
it is the platform’s to report. If every promise rejects, it rejects with the first
rejection in source order, with the rest attached as an array suppressed, as
__bynkSettleAll does; none is handed to waitUntil, since none is left running. A
chain a.race(b).race(c) lowers to one call over [a, b, c], so a nested race cannot
settle a microtask late and lose a tie. Like __bynkSettleAll, it is codegen, not part
of the published emit ABI (ADR 0310), and lives in the settle runtime module.
§7.4.16 The deliberate fault (#2620)
Section titled “§7.4.16 The deliberate fault (#2620)”unreachable(message) and todo(message) (§5.2)
lower to a call of __fault, the runtime half that raises them. It lives in the errors
runtime module beside invariantViolation.
export interface Fault { readonly kind: "Unreachable" | "Todo"; readonly message: string; readonly location: string;}
export function fault( kind: "Unreachable" | "Todo", message: string, location: string,): never;The contract: it throws an Error whose message reads <kind>: <message> (<location>)
and which carries the Fault record as its fault property. location is the call’s
project-relative path:line:col (the form an expect failure uses). A single-file compile, which has no project-relative path, reports offset <n> (the byte offset) instead. Because it returns
never, a call is an expression of any type, and inside an async body it rejects the
effect. It rides the same uncaught-fault channel as an invariant violation: the handler
faults, the agent’s commit does not happen, and the caller observes a fault, not an outcome;
a fault claim (§7.4.12a) holds for it. Like the other runtime helpers it is codegen, not
part of the published emit ABI (ADR 0310).
§7.4.17 The detach reporter (#3437)
Section titled “§7.4.17 The detach reporter (#3437)”__bynkDetach(promise, exec, site, errType?) is the runtime half of e.detach() (§5.5). promise
is the effect, already running, exec the execution context (deps.__exec), site the
path:line:col of the detach, and errType the display name of the error type when the
effect is an Effect[Result[_, E]]; it is absent for every other payload.
export function __bynkDetach( promise: Promise<unknown>, exec: { waitUntil(promise: Promise<unknown>): void; report?(record: Report): void }, site: string, errType?: string,): Promise<void>;The contract: it returns at once, never awaiting promise, after handing the effect to
exec.waitUntil. A failure is reported, never lost, by the runtime and not through Logger:
- A fault (the promise rejects) is passed on unchanged as a rejected promise into
waitUntil, the mechanism of the entry’s own fault report (#2192), so the platform records an exception with the original stack. The rejection is handled first, so a host that never awaitswaitUntilsees no unhandled rejection, andsiteis attached to an object reason asdetachedAt. - An
Err(whenerrTypeis present and the value’stagis"Err") is reported as one structuredconsole.errorrecord,{ message: "a detached effect returned Err", level: "error", fields: { site, type, variant } }, wherevariantis the error’stagwhen it is a sum, else empty. The payload is never reported, because it can hold a credential. Ok, and any payload that is not aResult, report nothing.
When exec has a report hook, as the test harness’s double does, each report is handed to it
and not logged, and it does not fail the case (ADR 0478). The cron, queue and email doubles
supply it too (#3541), so a detached Err there is counted in the case’s detached_failures.
A Bundle build has no platform to record an exception: its composition root hands handlers
__bynkProcessExec(), whose waitUntil reports a fault as one structured console.error
record, { message: "a detached effect faulted", level: "error", fields: { site, error } },
with site read from the reason’s detachedAt (empty for an effect abandoned by within).
Like __bynkSettleAll, it is
codegen, not part of the published emit ABI (ADR 0310), and lives in the settle runtime
module.