# Rastok documentation > Rastok is an open-source (Apache-2.0) integration platform written in Rust. An integration is written as a typed, declarative graph in a `.rkg` file: Operators transform data without side effects, Connectors talk to external systems under typed Contracts with declared outcomes, and the wiring, instances and bounded loops are checked by the compiler (`rastok check`). The same file holds the Lab: scenarios that script partner replies, faults and logical time, run deterministically on one machine without any external system (`rastok simulate`), and compared to sealed reference traces. The same program runs against real systems through Drivers (`rastok run`); every run leaves a causal journal that can be recorded and replayed without repeating its effects (`rastok replay`). Current public release: v0.2.0-alpha; the CLI installs from crates.io or the release archives (see Getting Started). Source revision: v0.2.0-alpha. ## Vocabulary - Graph: the application, a typed program of Nodes and explicit wiring, checked by the compiler before any run. - Operator: a Node that transforms and decides without touching the outside; Connector: the only Node that talks to an external system, under a typed Contract with declared outcomes. - Lab: the simulated world written in the same source file; scenarios inject inputs, script partner replies and faults, and advance logical time by instruction. - App: the same checked program run against real systems through Drivers, without a rewrite. - Journal: typed causal records of a run that link each output to the decision and input that caused it; a Lab scenario produces the same records on another machine, byte for byte. - Files: `.rkg` source, `.rkp` plan package, `.rkc` causal reference trace (golden), `.rkr` diagnostic recording replayed without Driver I/O. ## Minimal program The complete file that `rastok new starter` writes: one App graph with typed ports, one Operator with a handler, and a Lab with one scenario. No Connector, no external system. `rastok check starter.rkg` accepts it and `rastok simulate starter.rkg` prints `PASS starter.roundtrip_greeting`. Start from it rather than from the grammar. ```rkg graph starter : App { input in: string output out: string operator greet { input in: string output out: string on in { out = "Hello, " + data } } in -> greet -> out } lab starter { scenario roundtrip_greeting { app.in = "world" expect app.out == "Hello, world" } } ``` ## General - [Overview](https://docs.rastok.com/index.md): What Rastok is, what it is for and how it works: a situation every integration team knows, one file that outlives the project, one plan for two worlds, and a journal that explains every run. - [Getting Started](https://docs.rastok.com/getting-started.md): Install the current Rastok CLI, create a typed graph with a Lab scenario, and inspect a simulation without external services. - [The debugger, a guided tour](https://docs.rastok.com/debugger.md): Read a simulation or a recorded execution through its source, transitions, envelopes and assertions. - [AI Agents](https://docs.rastok.com/ai-agents.md): Read the documentation, the examples and their reference traces from a coding assistant through Markdown twins, llms.txt, content negotiation and the agent index. - [Migrating from 0.1 to 0.2](https://docs.rastok.com/migration.md): Port a 0.1 graph, handle missing values and check its scenarios against your existing reference traces. ## User Guide - [A program](https://docs.rastok.com/guide/01-a-program.md): Read a complete Rastok program by separating its Graph, Operators, Connectors, wiring and Lab. - [Types and expressions](https://docs.rastok.com/guide/02-types-and-expressions.md): Follow typed payloads through guards, narrowing and pure expressions without confusing text, bytes or decoded JSON. - [Connectors and outcomes](https://docs.rastok.com/guide/03-connectors-and-outcomes.md): Read a Connector Contract, choose a supported mode, and route data and terminal outcomes explicitly. - [The Lab: scenarios, mocks and time](https://docs.rastok.com/guide/04-the-lab.md): Describe inputs, boundary outcomes and elapsed time as executable scenarios while keeping the application graph unchanged. - [Running for real](https://docs.rastok.com/guide/05-running-for-real.md): Move from scripted outcomes to physical Drivers while keeping deployment settings, secrets, evidence and alpha limits explicit. - [Instances, state and time](https://docs.rastok.com/guide/06-instances-state-and-time.md): Choose the owner of state, separate instance keys from lifetimes, and make closure and bounded waiting explicit. - [Loops and retries: bounded recurrence](https://docs.rastok.com/guide/07-loops-and-retries.md): Separate authored state progression from safe repetition of one prepared Call, with explicit bounds, delays and terminal outcomes. - [Privacy, secrets and measurements](https://docs.rastok.com/guide/08-privacy-secrets-and-measurements.md): Classify typed data, bind credentials outside the graph, and retain exact business quantities on their original responses. - [Command line](https://docs.rastok.com/guide/09-command-line.md): Choose a Rastok command, supply its options, and distinguish read-only checks from real execution and file writes. - [When the answer is lost](https://docs.rastok.com/guide/10-when-the-answer-is-lost.md): Read a Call terminal, distinguish a lost answer from a refused operation, and choose what to tell the caller. ## Examples - [Echo: one graph, two worlds](https://docs.rastok.com/examples/01-echo.md): Run one graph with a real cat process or scripted Lab responses, then inspect a recording without starting the process again. - [File pipeline: effects with a contract](https://docs.rastok.com/examples/02-file-pipeline.md): Read a bounded file, reject an empty input, count its bytes and atomically replace a second file, then replay without disk access. - [Two tenants: whose state is this?](https://docs.rastok.com/examples/03-two-tenants.md): Watch Bob finish once while Alice alone times out, waits for backoff and retries in an isolated keyed instance. - [Webhook to partner: put it together](https://docs.rastok.com/examples/04-webhook-to-partner.md): Admit a webhook, validate and deduplicate it, then exercise bounded partner retries with privacy, secret and cost evidence. - [Sensor alarm: make time an input](https://docs.rastok.com/examples/05-sensor-alarm.md): Isolate hysteresis state by sensor, detect a missed heartbeat with a bounded join, and advance through a virtual day without waiting a day. - [Agent gateway: keep a conversation isolated](https://docs.rastok.com/examples/06-agent-gateway.md): Connect WebSocket conversations to resident JSONL processes, simulate interleaved app-server requests, and close one child without interrupting the other. - [Countdown: a bounded loop](https://docs.rastok.com/examples/07-countdown.md): Prove that a countdown terminates, follow its manager commands, and see the checker reject a measure that cannot prove progress. - [HTTP model adapter: typed responses and token metering](https://docs.rastok.com/examples/08-model-adapter.md): Select a typed view of an OpenAI Responses result, retain original token measurements by job and session, and distinguish absent usage from an observed zero. ## Reference - [Authoring rules](https://docs.rastok.com/reference/authoring-rules.md): Short examples of what check refuses or warns about, what to write, and where to find the rule. - [Types and schemas](https://docs.rastok.com/reference/types.md): Logical types, literal forms and the loss-checked JSON Schema, Avro, Arrow and OpenAPI projections shipped in the alpha. - [Expressions and dispatch](https://docs.rastok.com/reference/expressions.md): Operator precedence, built-in functions, narrowing, transaction dispatch and envelope writes accepted by the compiler. - [Standard contracts](https://docs.rastok.com/reference/contracts.md): Contract identities, modes, ports, terminal cases, settings and Lab support from the executable Connector catalogue. - [The Lab](https://docs.rastok.com/reference/lab.md): Executable Lab declarations, mock responses, scenario actions, observation windows and golden-trace commands. - [Diagnostics](https://docs.rastok.com/reference/diagnostics.md): Compiler error codes, their trigger, the source change to make, and message excerpts from exercised refusals. - [Standard library](https://docs.rastok.com/reference/stdlib.md): Find the types, Connector Contracts, annotations and value frontends supplied with Rastok. - [Execution and concurrency](https://docs.rastok.com/reference/execution.md): Distinguish instance ownership, concurrent external I/O and the execution model implemented by the current runtime. - [File](https://docs.rastok.com/reference/connectors/file.md): Ports, terminal outcomes, settings and qualification evidence for the File connector. - [Process](https://docs.rastok.com/reference/connectors/process.md): Ports, terminal outcomes, settings and qualification evidence for the Process connector. - [HttpClient](https://docs.rastok.com/reference/connectors/http-client.md): Ports, terminal outcomes, settings and qualification evidence for the HttpClient connector. - [HttpServer](https://docs.rastok.com/reference/connectors/http-server.md): Ports, terminal outcomes, settings and qualification evidence for the HttpServer connector. - [WebSocketClient](https://docs.rastok.com/reference/connectors/websocket-client.md): Ports, terminal outcomes, settings and qualification evidence for the WebSocketClient connector. - [WebSocketServer](https://docs.rastok.com/reference/connectors/websocket-server.md): Ports, terminal outcomes, settings and qualification evidence for the WebSocketServer connector. ## Specification - [Grammar](https://raw.githubusercontent.com/rastok-io/rastok/v0.2.0-alpha/docs/spec/grammar.md): the normative `.rkg` grammar, raw Markdown at revision v0.2.0-alpha. - [Specification index](https://raw.githubusercontent.com/rastok-io/rastok/v0.2.0-alpha/docs/spec/README.md): every specification chapter: expressions, instances, Loop, Retry, effects, simulation semantics, diagnostics, raw Markdown at revision v0.2.0-alpha. - [White paper](https://raw.githubusercontent.com/rastok-io/rastok/v0.2.0-alpha/WHITEPAPER.md): the design and its rationale, with the executable scope of the current alpha, raw Markdown at revision v0.2.0-alpha. ## Example sources Complete `.rkg` programs served as plain text, each with its Lab in the same file. Validate a copy with `rastok check ` and run its scenarios with `rastok simulate `. - [agent-chat](https://docs.rastok.com/examples/agent-chat.rkg) - [agent-dialogue](https://docs.rastok.com/examples/agent-dialogue.rkg) - [Agent gateway: keep a conversation isolated](https://docs.rastok.com/examples/agent-gateway.rkg): Connect WebSocket conversations to resident JSONL processes, simulate interleaved app-server requests, and close one child without interrupting the other. Chapter: https://docs.rastok.com/examples/06-agent-gateway.md - [HTTP model adapter: typed responses and token metering](https://docs.rastok.com/examples/agent-http.rkg): Select a typed view of an OpenAI Responses result, retain original token measurements by job and session, and distinguish absent usage from an observed zero. Chapter: https://docs.rastok.com/examples/08-model-adapter.md - [Countdown: a bounded loop](https://docs.rastok.com/examples/countdown.rkg): Prove that a countdown terminates, follow its manager commands, and see the checker reject a measure that cannot prove progress. Chapter: https://docs.rastok.com/examples/07-countdown.md - [csv-count](https://docs.rastok.com/examples/csv-count.rkg) - [Echo: one graph, two worlds](https://docs.rastok.com/examples/echo.rkg): Run one graph with a real cat process or scripted Lab responses, then inspect a recording without starting the process again. Chapter: https://docs.rastok.com/examples/01-echo.md - [File pipeline: effects with a contract](https://docs.rastok.com/examples/file-pipeline.rkg): Read a bounded file, reject an empty input, count its bytes and atomically replace a second file, then replay without disk access. Chapter: https://docs.rastok.com/examples/02-file-pipeline.md - [gauge](https://docs.rastok.com/examples/gauge.rkg) - [jsonl](https://docs.rastok.com/examples/jsonl.rkg) - [Two tenants: whose state is this?](https://docs.rastok.com/examples/keyed-retry.rkg): Watch Bob finish once while Alice alone times out, waits for backoff and retries in an isolated keyed instance. Chapter: https://docs.rastok.com/examples/03-two-tenants.md - [Sensor alarm: make time an input](https://docs.rastok.com/examples/sensor-alarm.rkg): Isolate hysteresis state by sensor, detect a missed heartbeat with a bounded join, and advance through a virtual day without waiting a day. Chapter: https://docs.rastok.com/examples/05-sensor-alarm.md - [Webhook to partner: put it together](https://docs.rastok.com/examples/webhook-to-partner.rkg): Admit a webhook, validate and deduplicate it, then exercise bounded partner retries with privacy, secret and cost evidence. Chapter: https://docs.rastok.com/examples/04-webhook-to-partner.md ## Full content --- title: "Echo: one graph, two worlds" description: Run one graph with a real cat process or scripted Lab responses, then inspect a recording without starting the process again. url: https://docs.rastok.com/examples/01-echo source_revision: v0.2.0-alpha --- # Echo: one graph, two worlds A line of text enters the program, and a real `cat` program, which repeats what it reads, sends it back. The line leaves the App through its output. There are two ways to run this program: the real world (App) starts `cat`; the virtual world (Lab) supplies its responses from a mock. The graph stays the same. You can test its success, filtering and timeout before starting an external process. The three [file formats](/guide/09-command-line.md#file-formats) have different jobs: `.rkg` is the program and its Lab, `.rkc` is a scenario's reference trace, and `.rkr` is a recording of a real execution. ## Run From the repository root, with `rastok` installed: ```sh rastok simulate examples/echo.rkg --compare examples/traces/echo ``` ```text PASS smoke.roundtrip PASS smoke.filtered PASS smoke.silence_expires 3 scenario(s), 0 failed ``` This reads `examples/echo.rkg` and compares each scenario with its reviewed file in `examples/traces/echo/`. The command starts no external process and writes no reference trace. To inspect the same scenario, use a binary built with `hosted-ui`: ```sh rastok simulate examples/echo.rkg --compare examples/traces/echo --ui ``` Open the complete URL printed by the CLI and keep it private. In Terminal on macOS, hold Command and double-click the URL to open it. If your terminal does not open links, copy the complete URL into your browser instead. The [debugger tour](/debugger.md) explains its controls and source view. ## Read the program Open `examples/echo.rkg` and read from top to bottom. `graph echo : App` declares the application. It contains a Connector and an Operator, with wiring between their ports. The Connector `shell : Process` talks to an external program under the [Process contract](/reference/connectors/process.md). Here `mode = job` starts a child for each Call, `command = "cat"` selects the program, and `codec = lines` exchanges lines of text. `timeout = duration("5s")` bounds the wait. The declarations of idempotence and deterministic behavior describe the repetition guarantee and the expected behavior of this command. The Operator `relay` does not start a process. Its `on in where data != ""` handler accepts a nonempty input and emits that data on `out`. An empty line produces no output. The wiring `in -> relay -> shell -> out` sends the App input to `relay`, then to `shell`, then to the App output. The two remaining outputs, `shell.err` and `shell.exit`, go to `nothing`: the program explicitly discards them. They still exist in the journal and can be checked by the Lab. Below the App, `lab smoke` describes the virtual world. It contains the shared mock and scenarios directly; no intermediate simulation block is needed. `mock shell` supplies the process response. In `on in { ... }`, `out = .` means “emit the data this mock received”: the dot is the received data, so the mock echoes it. `exit = Exited { exit_code = 0, signal = null }` then ends the simulated process successfully. See [mock responses](/reference/lab.md#mock-responses) for the other forms. The scenarios are independent: - `roundtrip` sends `"hello"`; `expect app.out == "hello"` requires exactly one matching App output, then `expect shell.err == nothing` requires no error output. - `filtered` sends `""`; `expect shell.in == nothing` and `expect app.out == nothing` check that the empty line reaches neither the process nor the App output. - `silence_expires` replaces the shared mock with `out = nothing`, providing no terminal response; `advance duration("5s")` moves virtual time and the final expectation checks `TimeoutExpired` on `shell.exit`. An [expectation](/reference/lab.md#expectations-and-windows) examines the observations since the preceding input or time advance. It does not consume them, so successive expectations can inspect the same window. Source: `examples/echo.rkg` ```rkg // A nonempty line goes to cat and comes back on the App output. // The Lab tests the echo, an empty line and a child that never answers. graph echo : App { connector shell : Process { mode = job ; command = "cat" codec = lines idempotent = true; behavior = deterministic timeout = duration("5s") } operator relay { on in where data != "" { out = data } } in -> relay -> shell -> out shell.err -> nothing shell.exit -> nothing } lab smoke { mock shell { on in { out = . exit = Exited { exit_code = 0, signal = null } } } scenario roundtrip { app.in = "hello" expect app.out == "hello" expect shell.err == nothing } scenario filtered { app.in = "" expect shell.in == nothing expect app.out == nothing } scenario silence_expires { mock shell { on in { out = nothing } } app.in = "hello" advance duration("5s") expect shell.exit == TimeoutExpired {} } } ``` ## Expected result The roundtrip scenario follows this sequence, with the Lab supplying the response instead of starting `cat`. ```mermaid sequenceDiagram participant lab as Lab: smoke.roundtrip participant app as echo participant relay as relay participant shell as shell: Process lab->>app: in = hello app->>relay: in = hello relay->>shell: out to in = hello shell->>lab: Scripted Call request lab-->>shell: out = hello, exit = Exited(0) shell-->>app: out = hello Note over shell: Exited is disposed to nothing ``` To run in the real world, use a macOS or Linux shell with `cat` on PATH. The following command starts `cat` and writes `echo.rkr` in your current directory. A recording captures the real execution so it can be inspected without starting that process again. Use an unused filename: existing recordings are never overwritten. ```sh printf 'hello\n' | rastok run examples/echo.rkg --record echo.rkr ``` ```text hello recorded: 8 causal records · seal 80f1263274f3b1b7480fdb13c007459e18e1e4cf10cc9bf08b5d12b63a4b7e0e ``` Echo has one App output, so stdout contains the value alone. The `recorded:` summary goes to stderr. Now inspect the recording: ```sh rastok replay echo.rkr ``` ```text replay: 8 causal records · seal 80f1263274f3b1b7480fdb13c007459e18e1e4cf10cc9bf08b5d12b63a4b7e0e · completed recording · no Driver I/O hello ``` Replay needs neither the original source nor `cat`. Its summary goes to stderr; the output value goes to stdout. The matching seals describe the same recorded execution, not a new call to the outside world. The seal above is from one run; compare your replay with the seal printed by your own run. A Lab execution and a real run do not have equal raw seals by default: their input provenance differs, and real response timing can differ from virtual time. Here the proof is equality between the real run and its recorded replay. ## Break it In `mock shell`, change exactly `out = .` to `out = "changed"`. Leave the expected value `"hello"` unchanged. Run: ```sh rastok simulate examples/echo.rkg --compare examples/traces/echo ``` ```text FAIL smoke.roundtrip expect app.out == "hello" (echo.rkg:34) observed app.out: "changed" expected 1 matching delivery on app.out, but observed 0 golden divergence: record 6: closure(32)[1][0][1][1]; expected 82066568656c6c6f; got 8206676368616e67…(10 bytes); cause: EGRESS "shell" · emitting_id 801cfc175b8f2151…(16 bytes) · call_key absent PASS smoke.filtered PASS smoke.silence_expires 3 scenario(s), 1 failed ``` Restore the checked-in source: ```sh git checkout -- examples/echo.rkg ``` That command discards your edits to this example. Then run the complete comparison again: ```sh rastok simulate examples/echo.rkg --compare examples/traces/echo ``` It prints the same three PASS lines and zero-failed total shown under Run. ## Read the golden difference The expectation names the source line, the observed `"changed"` value and the failed count. The golden difference names the first differing record, its field, the expected and actual encoded values, and the Call that produced it. Those are two checks: the assertion checks the authored expectation; the trace comparison checks the reviewed causal history. Do not save a new reference merely to make the comparison pass.
Inspect the raw sealed trace (.rkc) The versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence. Source: `examples/traces/echo/smoke.roundtrip.rkc` ```rastok-trace a6070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582024882066568656c6c6f09636c61620a000b000d81826c2e696e3e72656c61792e696e824982816572656c61798000 a7070211601282438280800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8 a80702116572656c617912824982816572656c6179800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c81822824382808000 a80702116572656c617912824982816572656c617980001364703a696e1481836c2e696e3e72656c61792e696e82438280800001178183636f757400a50150801cfc175b8f2151fe076d50a05c2b580250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582024882066568656c6c6f1818818201502d4efb509bf4e072a22ea0314c1c7ee11819818350801cfc175b8f2151fe076d50a05c2b587272656c61792e6f75743e7368656c6c2e696e82498281657368656c6c8000 a8070211657368656c6c1282498281657368656c6c800013676c3a737461727414801780181a50801cfc175b8f2151fe076d50a05c2b581822824382808000 a60703181b50801cfc175b8f2151fe076d50a05c2b58181c657368656c6c181e58208e4c7c1b99dbfd50e7a95185fead5ee1448fa904a2fdd778eaf5f2dbfd629a99181f0118217272656c61792e6f75743e7368656c6c2e696e a70703181b50801cfc175b8f2151fe076d50a05c2b58181c657368656c6c181e58208e4c7c1b99dbfd50e7a95185fead5ee1448fa904a2fdd778eaf5f2dbfd629a99181f02182082018282636f757482024882066568656c6c6f8264657869748202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f618217272656c61792e6f75743e7368656c6c2e696e a6070211657368656c6c1282498281657368656c6c80001364703a696e1481837272656c61792e6f75743e7368656c6c2e696e824982816572656c6179800001178283636f757400a50150233ee7a209d98e59c5f7b3aa16a9345a0250801cfc175b8f2151fe076d50a05c2b580350f3df1105112054d397a04ed0666ca4c804010582024882066568656c6c6f83646578697400a501509403fe6e10f58d02bd0e61df7a9d3e760250801cfc175b8f2151fe076d50a05c2b580350f3df1105112054d397a04ed0666ca4c80401058202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f6 seal 7e20cb99d172b4d2816136dfab6e60fadc99e592aa754a520059e2d4bfea5ea9 ```
## Carry forward For the concepts behind this example, read [A program](/guide/01-a-program.md) and [The Lab](/guide/04-the-lab.md). An injected fault belongs to the virtual world (Lab); the application stays the same as in the real world (App). Keep that distinction when a partner environment is not available yet. Next: [File pipeline](/examples/02-file-pipeline.md). Replace the external program with two file operations and ask what each effect is allowed to do. ## Limits Reference traces contain causal evidence. Recordings are bounded local diagnostics, not durable deployment journals or share-safe exports. The recorder currently refuses personal-data plans and boot-dependent deployment profiles. Diagnostic replay reconstructs recorded facts; it does not execute a Lab scenario. --- --- title: A program description: Read a complete Rastok program by separating its Graph, Operators, Connectors, wiring and Lab. url: https://docs.rastok.com/guide/01-a-program source_revision: v0.2.0-alpha --- # A program After this chapter you can read a small `.rkg` file, identify where its decisions and external work belong, and check its wiring without starting the external program. ## Start with one boundary Open `examples/echo.rkg` in the checkout. Its first declaration is a Graph named `echo`. A Graph contains children and the connections between them. It also defines the boundary through which the surrounding program can send and receive data. Its children own the application handlers and private `var` state. The `: App` annotation attaches the App Extension. It marks this Graph as the public root of the compiled unit. There must be exactly one such root among the files compiled together. A unit can span several files; this example fits in one. This is the complete Graph, from `examples/echo.rkg`, lines 5–22: ```rkg graph echo : App { connector shell : Process { mode = job ; command = "cat" codec = lines idempotent = true; behavior = deterministic timeout = duration("5s") } operator relay { on in where data != "" { out = data } } in -> relay -> shell -> out shell.err -> nothing shell.exit -> nothing } ``` ## Read declarations before connections The `relay` Operator owns the decision. Its handler reacts to an envelope on `in`; `data` refers to that envelope's payload. The guard rejects the empty string. On the accepted path, assigning to `out` emits the payload. Operators perform pure computation and may keep declared private state; this one needs none. The `shell` Connector owns the external boundary. `Process` names its Contract, while `mode = job` selects a finite child-process invocation. `command` and `codec` describe the requested external work and framing. The timeout bounds waiting for that invocation. The compiler checks these settings against the Process Contract. A Driver implements the Contract. With `run`, the physical Process Driver starts `cat`. With `simulate`, a Lab mock supplies its outcomes. The Operator and the wiring remain the same. ## Account for every possible output The final three lines are the wiring. `->` carries values in one direction. A bare Node name in a route means its `out` port as a source and its `in` port as a destination; any other port is written `node.port`. An Operator input reached by a route needs an `on` handler or a join that names it. The App input feeds `relay`, its accepted output feeds `shell`, and the echoed text crosses the App output boundary. The two remaining outputs matter. Process `err` carries stderr, while `exit` carries the typed terminal outcome of the invocation, including a timeout. Both are explicitly sent to `nothing`. That is a deliberate discard, not an unwired output that the runtime happens to ignore. Every output the compiler considers possible needs a destination. A statically proven impossible output is exempt. Removing either discard from this Graph produces `E-UNWIRED-OUTPUT`. A discarded emission remains visible in the journal and in Lab expectations. The journal is not a log ordered by the clock: it links each output to the decision and the input that caused it; the [Overview](/index.md#what-a-run-leaves-behind) contrasts the two. ## Check before running From the repository root: ```sh rastok check examples/echo.rkg ``` The command checks the source and reports its Node count and semantic hash. It does not start `cat`, and it does not write a separate plan file that you must pass to the next command. The accepted plan contains resolved types, declarations and wiring for the runtime to interpret. The rest of this source file is `lab smoke`. It supplies scenarios for the same App, including the empty input and a silent process. Run those with `rastok simulate examples/echo.rkg`. Each scenario records the graph's transactions and the scripted boundary outcomes. Adding a scenario does not change the program's semantic hash: the Lab is not deployed. The normative sources are [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md) for declarations and [`docs/spec/delivery-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/delivery-semantics.md) for output dispositions. The conceptual model is also explained in `WHITEPAPER.md`, section 2. The current scope remains an experimental alpha; read [what is available today](/index.md#what-is-available-today) before treating a successful example as a deployment guarantee. ## Summary - A Graph contains Nodes and wiring; `App` marks the public root. - An Operator decides; a Connector crosses a declared external boundary. - Every possible output has an explicit destination. - Checking, simulation and real execution are different commands over the same source program. ## Next Continue with [Types and expressions](/guide/02-types-and-expressions.md) to read the values carried by those connections. For the hands-on mirror, run [Echo](/examples/01-echo.md), change its mock and inspect the first golden difference. --- --- title: Overview description: "What Rastok is, what it is for and how it works: a situation every integration team knows, one file that outlives the project, one plan for two worlds, and a journal that explains every run." url: https://docs.rastok.com/ source_revision: v0.2.0-alpha --- # Overview ## What is Rastok? An integration rarely breaks on the happy path. It breaks on the edge cases: unavailable dependencies, unexpected replies, missing or incomplete tests. With AI, writing a flow has never been faster; keeping it correct and stable over time is another story. **Rastok is a simulation-first integration platform.** The specification and exhaustive scenarios are written together, in a dedicated, strict language. The same program runs in a simulated world, then, without a rewrite, in the real one. Here the simulated world is the Lab and the real one is the App. One file holds the flow, the scenarios that test it, faults included, and a journal that explains each run. Within the supported Contract and Lab profiles, the same checked program runs against scripted partners in the Lab or against real systems in the App, without rewriting the graph. You write `.rkg` programs. Rastok itself is written in Rust; you do not need Rust to use it. This page is the map. [Getting started](/getting-started.md) installs the tool and opens the two paths: the user guide, or the [examples](/examples/01-echo.md). ## What it is for Most of an integration's life happens in the Lab. Write the flow and its scenarios, faults included; simulate; fix, or add a scenario; simulate again. That loop needs no partner environment. Confronting the real systems is slow and expensive, so it comes after the simulation, not instead of it: acceptance with real Drivers once the scenarios pass, then production, where an incident is recorded and comes back into the Lab as one more scenario. ```mermaid flowchart LR subgraph lab ["Virtual world (Lab): where most of the time goes"] design["Design or change: the flow and its scenarios, faults included"] --> simulate["Simulate: scripted partners, virtual time, compared against the goldens"] simulate --> design end simulate -.->|"once the scenarios pass"| acceptance["Acceptance: the same program, real Drivers"] acceptance -.->|"in production"| incident["Incident: recorded facts, replayed"] incident -.->|"one more scenario"| design ``` | Moment | What teams usually have | What the file gives | |---|---|---| | Design | A partner that is not ready, a contract nobody has exercised | A scripted partner in the Lab, with fault scenarios from the first day | | Change | The fear of breaking what works | `--compare` against the reviewed goldens, with the first divergence named | | Acceptance | A second version of the flow for the real environment | The same checked program, with real Drivers | | Incident | Logs that say what happened, not why | Recorded facts, replayed without side effects, then a scenario that reproduces them | The alpha does not automatically convert a recording into a Lab scenario: writing the scenario is a human step. Keep it, with its reviewed golden, so the next change can be checked against it. ## At a glance - Types include exact decimals, timestamps with and without zones, structs, arrays, maps and unions; projections target JSON Schema, Avro, Arrow and OpenAPI. [Types and schemas](/reference/types.md), [guide](/guide/02-types-and-expressions.md) - Use `is` to test a typed value, `as?` to try a conversion and `in` to test array elements or map keys. Wiring provides bounded static fan-out. [Expressions and dispatch](/reference/expressions.md) - Keys scope instances by tenant, sensor or event, with `persistent`, `idle`, `age`, `once` and `slot` lifetimes, and joins bound waiting. [Instances, state and time](/guide/06-instances-state-and-time.md) - Loop can prove termination through a decreasing measure; Retry checks the safe-repetition rule. [Loops and retries](/guide/07-loops-and-retries.md) - Typed Contracts define HTTP/1.1 to HTTP/3 (HTTP/3 behind the `hosted-http3` feature), WebSocket, process and file exchanges. [Standard contracts](/reference/contracts.md), [guide](/guide/03-connectors-and-outcomes.md) - The Lab supplies mocks, scenarios, virtual time, injected faults and golden traces. [The Lab](/reference/lab.md), [guide](/guide/04-the-lab.md) - The journal records execution; recording, replay and the debugger expose those facts for inspection. [Running for real](/guide/05-running-for-real.md) - Schema annotations declare personal data, secrets and measurements. [Privacy, secrets and measurements](/guide/08-privacy-secrets-and-measurements.md) - The core evaluates deterministically, without a clock, network or randomness, on targets without an operating system. [How it works](#how-it-works) ## How it works ### The smallest program `examples/echo.rkg` is a whole integration in one file. A nonempty line of text enters; under `rastok run`, a real `cat` process echoes it and the echo leaves. ```rkg graph echo : App { connector shell : Process { mode = job ; command = "cat" codec = lines idempotent = true; behavior = deterministic timeout = duration("5s") } operator relay { on in where data != "" { out = data } } in -> relay -> shell -> out shell.err -> nothing shell.exit -> nothing } ``` Three kinds of Node appear here, and one Extension. - `graph echo : App` is the **Graph**: a typed boundary, its children and their static wiring. A Graph owns scope and lifetime; it has no application handler. `App` is the **Extension** that marks the public root. - `operator relay` is an **Operator**: the decision. A typed transition that may keep private state and never performs external I/O. - `connector shell : Process` is a **Connector**: an explicit boundary to the outside, under one exact, versioned **Contract**. A **Driver** implements the Contract: a real process in the App, a script in the Lab. - `shell.err -> nothing` and `shell.exit -> nothing` are decisions the compiler can see. Every output the compiler considers possible needs an explicit destination, including `nothing` for a deliberate discard. An output proven impossible needs no destination. Two other Extensions exist in the alpha. `Loop` adds finite recurrence over time. `Retry` repeats the same outbound Call under a bounded policy the compiler checks. The executable standard Contract families are `Process`, `File`, `HttpClient`, `HttpServer`, `WebSocketClient` and `WebSocketServer`; `rastok connectors` lists their modes, installed implementations, Lab bindings and untested cases. The [standard library reference](/reference/stdlib.md) lists the types, Contracts, annotations and value frontends available to a program. The Lab lives in the same file. This is the scenario that tests the fault case, a process that never answers: ```rkg scenario silence_expires { mock shell { on in { out = nothing } } app.in = "hello" advance duration("5s") expect shell.exit == TimeoutExpired {} } ``` Time is an input: `advance` moves the virtual clock by five seconds and the timeout becomes a typed fact the scenario asserts. No process starts. Adding a scenario changes nothing in the program's identity: the Lab is part of the source, not of the semantic hash. The [first example](/examples/01-echo.md) runs this file, breaks it and reads the result. ### One source, one plan, two worlds The real world (App) and the virtual world (Lab) use different Drivers around the same compiled graph and journal semantics. ```mermaid flowchart TD source["flow.rkg: graph and Lab scenarios"] --> compiler["Compiler: types, wiring, Contracts"] compiler --> plan["One executable plan"] plan --> lab["Virtual world (Lab): scripted outcomes, virtual time"] plan --> app["Real world (App): physical Drivers, elapsed time"] lab --> journal["Journal: what came in, what was decided, what went out"] app --> journal ``` Each command compiles the source; `rastok check` validates it, rather than writing a plan file that the other commands require. The compiler rejects an ill-typed or badly wired graph before it runs. What it accepts becomes a plan: tables and expression trees, not generated code. The runtime interprets that plan. `rastok simulate` supplies scripted boundary responses and virtual time; `rastok run` uses physical Drivers and explicit elapsed time. The core reads no clock, network or randomness: CI checks it for three targets without an operating system and builds and runs the RP2350 spike under Cortex-M33 emulation; [Sensor alarm](/examples/05-sensor-alarm.md#carry-forward) states the tested boundary and the physical-board limit. ### The rule that makes two worlds possible Operators decide. Connectors act. Outcomes return as typed observations that execution records in the journal. This is the conceptual separation, not the signature of a public API: ```text step(plan, state, event) -> (new_state, effect_intents) Driver execution : effect_intents -> real outcomes Lab simulation : effect_intents -> controlled outcomes ``` The runtime commits an outbound obligation before asking its Driver to perform the effect. A scripted partner can therefore stand in for one that is not ready. Supported faults and timeouts become scenarios, while the same checked program can later use real Drivers. ### What a run leaves behind Execution writes an in-memory journal. It is not a log. | A log | The journal | |---|---| | Orders events by the machine clock | Links each output to the decision and the input that caused it | | Differs at every run: timestamps, latencies, interleavings | For the same scenario, the same records on another machine, byte for byte | | Says what happened; the reader guesses why | Keeps the whole chain from cause to effect | That chain is what *causal* means on this site: typed records, in causal order, for what came in, what was decided and what went out. Three things use the journal. ```mermaid flowchart LR labJournal["Lab run journal"] --> golden["Golden trace, versioned with the flow"] golden --> compare["simulate --compare: first divergence"] appJournal["App run journal"] --> recording["--record: diagnostic recording"] recording --> replay["rastok replay: same facts, no Driver I/O"] labJournal --> ui["--ui: paused debugger"] replay --> ui ``` - **Golden traces.** A scenario's journal is projected into a canonical trace. Save it, review it and version it with the flow. `rastok simulate flow.rkg --compare ` reports the first divergence for each differing scenario. For the same program, equal ingress provenance, ordered inputs and boundary outcomes, and observable logical time give equal causal facts. Real runs and Lab runs use different ingress provenance by default; matching displayed output alone does not give matching trace seals. - **The debugger.** `rastok simulate flow.rkg --ui` starts paused. Forward controls advance the simulation and record transitions; history navigation inspects those recorded transitions. It does not edit the flow or fork another world. `run --ui` is not supported. - **Recordings.** `rastok run flow.rkg --record capture.rkr` captures a real run. `rastok replay capture.rkr`, optionally with `--ui`, reconstructs the recorded state without any Driver I/O. Recordings are bounded, sensitive local files, not a durable deployment journal. The current recorder refuses personal-data plans, nonempty deployment attestations and boot-dependent Connector settings. ## What Rastok is not - Not a durable workflow engine yet. The journal is in memory; durable storage is later work. - Not an exhaustive catalogue of ready-made connectors. Six standard Contract families are executable today. `rastok connectors` lists modes, support and installed implementations; declared but non-executable families are marked as deferred. - Not a visual designer. The source is text, versioned in Git. The debugger explains recorded execution; it does not edit the flow. - Not a proof about the outside world. Passing a simulation does not prove that an external system honors its Contract, or make the alpha production-ready. ## What is available today Checked for `v0.2.0-alpha`, 1 December 2026. Rastok is experimental. `rastok check` requires a lifetime for each keyed node and checks reads of array elements and map keys that might be absent. The gallery has eight runnable examples, including the resident gateway and typed HTTP model adapter. The deployment journal is in memory. Diagnostic replay restores recorded facts without repeating external effects; it does not restart a stopped deployment. Planned work includes a durable local journal for recovery and a way to turn a real incident into a replayable Lab scenario. The full opening qualification remains in progress. No reading-time claim is made before independent installation trials. ## Vocabulary | Term | Meaning | |---|---| | Graph | Typed boundary, children and wiring; owns scope and lifetime | | Operator | Typed transition with private state; no external I/O | | Connector | Explicit boundary to an external system, under one Contract | | Contract | Exact, versioned interface of a Connector | | Driver | Implementation of a Contract: physical in the App, scripted in the Lab | | Extension | Protocol attached to one Node; executable here: `App`, `Loop`, `Retry` | | Lab | Scenarios that script boundary outcomes, time and faults | | Plan | The compiled, executable form of a program | | Semantic hash | Identity of the program, independent of formatting and of the Lab | | Journal | Typed causal records and unsealed recovery evidence of a run | | Golden trace | Versioned canonical projection of a scenario's journal | | Recording | Captured real run, replayable without Driver I/O | ## Where to go next Start with [Authoring rules](/reference/authoring-rules.md) for short examples of common refusals. The rest of the Reference covers types, expressions, Contracts, Lab syntax and diagnostics. - Install and run a first graph: [getting started](/getting-started.md). - The short route through the examples: [echo](/examples/01-echo.md), then [webhook to partner](/examples/04-webhook-to-partner.md). - The normative specification and architecture notes live in the repository, under `docs/spec` and `docs/architecture`. --- --- title: Authoring rules description: Short examples of what check refuses or warns about, what to write, and where to find the rule. url: https://docs.rastok.com/reference/authoring-rules source_revision: v0.2.0-alpha --- # Authoring rules Use these pairs when writing a graph or reading a refusal. The left column is code to diagnose, not a template. A warning still allows the graph to run. | Rule | Refused or warned | Write instead | Diagnostic | |---|---|---|---| | [Render an integer](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#14-rendering-a-value-as-text) | `data as string` | `string(data)` | `E-EXPR` | | [Narrow a uint to int](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/types.md#numeric-widening-and-the-common-type) | `data as int` | `(data as? int).orValue(0)` | `E-EXPR` | | [Read an array](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#15-absence) | `data[0]` | `data[?0].orValue("none")` | `E-EXPR` | | [Read a map field](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#15-absence) | `data.name` | `data.?name.orValue("none")` | `E-EXPR` | | [Read a schemaless JSON object](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#5-narrowing) | `out = data is Receipt` | `val receipt = data as? Receipt; out = receipt != null` | `E-EXPR` | | [Initialize state](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md#4-mutable-state-has-one-executor-owner) | `var last: string` | `var last: string = ""` | `E-EXPR` | | [Test array membership](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#11-compatibility-oracle-and-divergence-ledger) | `data.exists(x, x == "red")` | `"red" in data` | `E-EXPR` | | [Test a map key](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#11-compatibility-oracle-and-divergence-ledger) | `1 in data` | `"id" in data` | `E-EXPR` | | [Build an array](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#11-compatibility-oracle-and-divergence-ledger) | `["a"] + ["b"]` | `["a", "b"]` | `E-EXPR` | | [Test a string](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md#1-expression-contract) | `data.matches("^a.*b.*c$")` | `data.startsWith("a") && data.contains("b") && data.endsWith("c")` | `E-EXPR` | | [Choose when a key expires](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md#6-lifetime) | `instance = { key = data }` | `instance = { key = data }; lifetime = { kind = idle; max = duration("5m") }` | `E-LIFETIME-REQUIRED` | | [Close an outbound Call](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md#71-the-bounded-closing-contract) | `lifetime = { kind = once }` | `lifetime = { kind = once }; closing = { drain_for = duration("1s"); settle_for = duration("1s") }` | `E-INSTANCE` | | [Discard a lost answer](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/delivery-semantics.md#44-recovery--a-triage-not-a-gamble) | `_ => out = "failed"` | `_ => nothing` | `W-MATCH-CATCHALL` | | [Mock HTTP 204](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md#32-httpclient--outbound-http) | `out = "body"; exit = Completed { status = 204 }` | `exit = Completed { status = 204 }` | `E-CONTRACT-REQUIRED` | | [Mock HTTP 205](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md#32-httpclient--outbound-http) | `out = "body"; exit = Completed { status = 205 }` | `exit = Completed { status = 205 }` | `E-CONTRACT-REQUIRED` | | [Describe a codec refusal](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md#32-httpclient--outbound-http) | `exit = DecodeFailed {}` | `exit = DecodeFailed { message = "expected a status" }` | `E-PORT-TYPE` | `int` and `uint` are signed and unsigned 32-bit integers. Either fits a `long`; a computed `long` need not fit either narrower type. For an array received at a port, even index zero might be absent. Choose a fallback only if it means something for your application; otherwise handle null separately. A schemaless JSON codec delivers an object as a map. If it does not fit `Receipt`, `receipt` is null. Use `is` for a typed union or its case. An HTTP timeout does not prove that the operation failed. If you record an outcome instead of dropping it, name each lost-answer case the warning lists before the wildcard, even if several cases go to the same destination. For example, this handler distinguishes an unknown outcome from a known failure: ```rkg on in match data { Completed => out = "answered" BodyTooLarge | DecodeFailed | OutcomeUnknown | ProtocolFailed | TimeoutExpired => out = "unconfirmed" _ => out = "failed" } ``` Lifetime choices are `persistent`, `idle`, `age`, `slot` and `once`. A finite owner with an outbound Connector also declares its closing budgets. A 204 or 205 has a terminal but no body. A codec refusal carries a message about the expected data, not a copy of the value received. ## Specified, not shipped | Not available | Alternative in this release | |---|---| | The iteration macro `exists` | Use [membership](/reference/expressions.md#operators) for an element or key. | | Array concatenation with `+` | Construct the known elements explicitly. There is no general concatenation operator. | --- --- title: File description: Ports, terminal outcomes, settings and qualification evidence for the File connector. url: https://docs.rastok.com/reference/connectors/file source_revision: v0.2.0-alpha --- # File `std/file@1`. One file operation per Call. `read` publishes complete bytes; `replace` stages and atomically replaces one file. Directory operations are outside this Contract. ## Declaration This declaration comes from `examples/file-pipeline.rkg`. Place the Connector in a Graph and wire its ports; the excerpt alone is not an App. Its App input is `string`: each producer of `read_file.in` must supply a string for the plain `data as string` in the path setting to be safe. ```rkg connector read_file : File { mode = read path = data as string max_read = "64KiB" timeout = duration("2s") } ``` The [contract index](/reference/contracts.md) explains shared settings, build features and the distinction between a Contract, a Lab model and an installed Driver. Selector: `mode` is required. Calls on one instance are serialized; [queue time counts toward `timeout`](/reference/execution.md#instances-own-state-not-threads). | Mode | Driver direction | Exchange | Lab model | Installed in this binary | |---|---|---|---|---| | `read` | outbound | call | `lab-call` | `file` | | `replace` | outbound | call | `lab-call` | `file` | ## Ports and completion | Mode | Port | Direction | Type rule | |---|---|---|---| | read | `in` | input | `variant` | | read, replace | `out` | output | `array` | | read, replace | `exit` | output | FileExit, below | | replace | `in` | input | `array` | | Mode | Output cardinality | |---|---| | read | `out`: exactly one on `Completed`; exactly one final `exit` per Call | | replace | `out`: never; exactly one final `exit` per Call | ## Exit union | Case | Payload | Call visibility | |---|---|---| | `AtomicReplaceUnavailable` | Empty | before_effect | | `Completed` | Empty | after_effect | | `InvalidPath` | Empty | before_effect | | `IoFailed` | Empty | outcome_unknown | | `NotAFile` | Empty | before_effect | | `NotFound` | Empty | before_effect | | `OutcomeUnknown` | Empty | outcome_unknown | | `PermissionDenied` | Empty | before_effect | | `ReadLimitExceeded` | `{ limit: ulong }` | after_effect | | `TimeoutExpired` | Empty | outcome_unknown | ## Settings | Mode | Setting | Domain | Presence / default | Latest phase | |---|---|---|---|---| | read, replace | `path` | `string` | required | invocation | | read, replace | `idempotent` | `bool` | `true` | plan | | read, replace | `behavior` | `deterministic` | `deterministic` | plan | | read, replace | `timeout` | `duration` | optional | instance | | read | `max_read` | `ByteSize` | `"8MiB"` | plan | File paths are logical paths relative to the deployment root. A replacement has no truncate fallback and makes no crash-durability promise. The checker fixes File repetition to idempotent and behavior to deterministic. ## Qualification inventory `read`: fixture `crates/rastok/tests/conformance_file.rs`. Cases without a portable forced fixture: `PermissionDenied`, `AtomicReplaceUnavailable`, `IoFailed`, `TimeoutExpired`, `OutcomeUnknown`. Related tests: `crates/rastok/tests/file_connector.rs`. `replace`: No dedicated full-Contract fixture is declared. Related tests: `crates/rastok/tests/file_connector.rs`. --- --- title: "File pipeline: effects with a contract" description: Read a bounded file, reject an empty input, count its bytes and atomically replace a second file, then replay without disk access. url: https://docs.rastok.com/examples/02-file-pipeline source_revision: v0.2.0-alpha --- # File pipeline: effects with a contract This program reads a file, counts its bytes and copies nonempty content to another file. Echo separated computation from the world. Now the world contains files you could overwrite. How do you make the permitted operation, its limits and its refusals visible before the flow runs? The [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for the program and Lab, `.rkc` for a reviewed scenario reference and `.rkr` for a real execution recording. ## Run From the repository root, with `rastok` installed: ```sh rastok simulate examples/file-pipeline.rkg --compare examples/traces/file-pipeline ``` ```text PASS files.copy PASS files.empty PASS files.utf8 PASS files.directory PASS files.single_byte 5 scenario(s), 0 failed ``` For the controls and source view, see [the debugger tour](/debugger.md). ## Read the program Find the two [File](/reference/connectors/file.md) Connectors: one reads, one replaces. Their modes describe different operations under the same Contract. Between them, the Operator decides whether the bytes should continue. Follow the `exit` routes too: a refused read has a destination, rather than disappearing into a log. The Lab replaces both file operations, using the same resolved port types. In a port declaration, the name after `:` is its payload's type: the values it may accept or emit. `output failed: FileExit` declares an output port named `failed`, not a new type. See the [type reference](/reference/types.md) for the notation. `FileExit` comes from the [standard library](/reference/stdlib.md#types), without an import or copied declaration; its cases are the ones on File's `exit` port. The [Lab reference](/reference/lab.md) explains mock responses, expectations and observation windows. `advance` supplies virtual time; a mock's terminal response ends its simulated exchange, not the whole scenario. Source: `examples/file-pipeline.rkg` ```rkg // Bounded File read, byte count and empty-file validation, atomic replacement. // The deployment root is supplied by --file-root; the Lab never opens a file. graph file_pipeline : App { input in: string output bytes_read: int output empty: bool output failed: FileExit // Standard-library type; no import is needed. connector read_file : File { mode = read path = data as string max_read = "64KiB" timeout = duration("2s") } operator inspect { input in: array output accepted: array output bytes_read: int output empty: bool on in match { size(data) > 0 => { bytes_read = size(data); accepted = data } _ => empty = true } } connector write_file : File { mode = replace path = "copy.txt" timeout = duration("2s") } in -> read_file -> inspect inspect.accepted -> write_file inspect.bytes_read -> bytes_read inspect.empty -> empty write_file.out -> nothing read_file.exit -> match { Completed -> nothing AtomicReplaceUnavailable | InvalidPath | IoFailed | NotAFile | NotFound | OutcomeUnknown | PermissionDenied | ReadLimitExceeded | TimeoutExpired -> failed } write_file.exit -> match { Completed -> nothing AtomicReplaceUnavailable | InvalidPath | IoFailed | NotAFile | NotFound | OutcomeUnknown | PermissionDenied | ReadLimitExceeded | TimeoutExpired -> failed } } lab files { mock read_file { on in { out = base64! { YWxwaGEKYmV0YQo= }; exit = Completed {} } } mock write_file { on in { exit = Completed {} } } scenario copy { app.in = "input.txt" expect app.bytes_read == 11 expect write_file.in where size(data) == 11 expect app.failed == nothing } scenario empty { mock read_file { on in { out = base64! {}; exit = Completed {} } } app.in = "empty.txt" expect app.empty expect write_file.in == nothing } scenario utf8 { mock read_file { on in { out = base64! { w6kK }; exit = Completed {} } } app.in = "utf8.txt" expect app.bytes_read == 3 expect write_file.in where size(data) == 3 expect app.failed == nothing } scenario directory { mock read_file { on in { exit = NotAFile {} } } app.in = "directory" expect app.failed where data is NotAFile expect write_file.in == nothing } scenario single_byte { mock read_file { on in { out = base64! { eA== }; exit = Completed {} } } app.in = "single-byte.txt" expect app.bytes_read == 1 expect write_file.in where size(data) == 1 expect app.empty == nothing expect app.failed == nothing } } ``` ## Expected result In `files.copy`, both File Calls use Lab responses; the count is emitted before the accepted bytes reach `write_file`. ```mermaid sequenceDiagram participant lab as Lab: files.copy participant app as file_pipeline participant read as read_file: File participant inspect as inspect participant write as write_file: File lab->>app: in = input.txt app->>read: in = input.txt read->>lab: Scripted read request lab-->>read: 11 bytes, then Completed read->>inspect: out to in = alpha\nbeta\n inspect-->>app: bytes_read = 11 inspect->>write: accepted to in = the same bytes write->>lab: Scripted replace request for copy.txt lab-->>write: Completed Note over read,write: Completed exits are disposed to nothing ``` The Lab supplies `alpha\nbeta\n`: eleven bytes. The Operator counts them and forwards a nonempty value to the replacement File Connector. Empty input does not overwrite the target. A directory produces `NotAFile`, routed to `failed`. The `utf8` scenario counts `é\n` as three bytes, not two characters: the reader's `array` port determines how the value is read. `single_byte` supplies `x`, exactly one byte, and checks that it reaches the writer rather than the `empty` output. This is the smallest input accepted by `size(data) > 0`. To exercise real disk I/O, use a macOS or Linux shell with `mktemp`, `printf` and `cmp` on PATH. This creates a new temporary directory; both file operations are confined to that directory, and the recording uses an unused path: ```sh demo_root=$(mktemp -d) printf 'alpha\nbeta\n' > "$demo_root/input.txt" printf 'input.txt\n' | rastok run examples/file-pipeline.rkg --file-root "$demo_root" --record "$demo_root/copy.rkr" cmp "$demo_root/input.txt" "$demo_root/copy.txt" printf 'changed after recording\n' > "$demo_root/input.txt" rastok replay "$demo_root/copy.rkr" ``` This run printed the following values. Compare the seal from your run with the seal from its replay: ```text bytes_read: 11 recorded: 12 causal records · seal bfa1df6bc5ab7eaeb42419aa0203af9b5350ee0e4252f96ed4fcb2c4159f7977 ``` `cmp` exited successfully without output. After changing the input file, replay printed: ```text replay: 12 causal records · seal bfa1df6bc5ab7eaeb42419aa0203af9b5350ee0e4252f96ed4fcb2c4159f7977 · completed recording · no Driver I/O bytes_read: 11 ``` Replay prints the same recorded output and seal without reading or replacing either file. It does not restore the disk to its earlier contents. Use `rastok replay "$demo_root/copy.rkr" --ui` to inspect the recorded history. ## Break it Change `size(data) > 0` to `size(data) > 1`. The one-byte input is now rejected as empty, but the other four scenarios still pass. Run the comparison: ```sh rastok simulate examples/file-pipeline.rkg --compare examples/traces/file-pipeline ``` ```text PASS files.copy PASS files.empty PASS files.utf8 PASS files.directory FAIL files.single_byte expect app.bytes_read == 1 (file-pipeline.rkg:84) nothing observed expected 1 matching delivery on app.bytes_read, but observed 0 expect write_file.in where size(data) == 1 (file-pipeline.rkg:85) nothing observed where size(data) == 1 is false for 0 of 0 deliveries; count 0, expected 1 expect app.empty == nothing (file-pipeline.rkg:86) observed app.empty: true expected no deliveries on app.empty, but observed 1 golden divergence: record 7: emissions(23)[0][0]; expected "bytes_read"; got "empty"; cause: TRANSACTION "inspect" · trigger "p:in" · cause_id absent 5 scenario(s), 1 failed ``` Restore the checked-in source (this discards your edits to this example): ```sh git checkout -- examples/file-pipeline.rkg ``` ## Read the golden difference The first changed Operator transaction names its changed emission and causal input. In `single_byte`, the byte count and writer assertions fail, and the `empty` output appears where the scenario expects none. The assertions fail even without `--compare`; the golden also locates the first changed record. A passing scenario tests the inputs and responses it supplies, not every possible value. The earlier empty, three-byte and eleven-byte cases could not distinguish `> 0` from `> 1`. The one-byte case adds that boundary to the reviewed examples. A golden comparison does not prove two programs equivalent for inputs absent from the Lab. Restore the threshold and compare again.
Inspect the raw sealed trace (.rkc) The versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence. Source: `examples/traces/file-pipeline/files.copy.rkc` ```rastok-trace a6070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582024c820669696e7075742e74787409636c61620a000b000d8182702e696e3e726561645f66696c652e696e824d828169726561645f66696c658000 a7070211601282438280800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8 a807021169726561645f66696c6512824d828169726561645f66696c65800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c81822824382808000 a60703181b50f3df1105112054d397a04ed0666ca4c8181c69726561645f66696c65181e58204871ffb86d08c9280e24baa4c587dad86a9970eee2bdf74bc788acdab0e5dc1f181f011821702e696e3e726561645f66696c652e696e a70703181b50f3df1105112054d397a04ed0666ca4c8181c69726561645f66696c65181e58204871ffb86d08c9280e24baa4c587dad86a9970eee2bdf74bc788acdab0e5dc1f181f02182082018282636f757482024e82054b616c7068610a626574610a82646578697482025082138269436f6d706c65746564820f801821702e696e3e726561645f66696c652e696e a707021169726561645f66696c6512824d828169726561645f66696c6580001364703a696e148183702e696e3e726561645f66696c652e696e82438280800001178283636f757400a5015077caecb1cc181b62e2b991b703bb4c7f0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582024e82054b616c7068610a626574610a83646578697400a50150b80b3a765394a1c849ad18cc90b9659d0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582025082138269436f6d706c65746564820f80181981835077caecb1cc181b62e2b991b703bb4c7f7818726561645f66696c652e6f75743e696e73706563742e696e824b828167696e73706563748000 a807021167696e737065637412824b828167696e7370656374800013676c3a737461727414801780181a5077caecb1cc181b62e2b991b703bb4c7f1822824382808000 a807021167696e737065637412824b828167696e737065637480001364703a696e1481837818726561645f66696c652e6f75743e696e73706563742e696e824d828169726561645f66696c658000011782836a62797465735f7265616400a5015020f4693e7f501632f25c434a0371050b025077caecb1cc181b62e2b991b703bb4c7f0350f3df1105112054d397a04ed0666ca4c804010582024382020b8368616363657074656400a5015099f25f558f929e9517b51ebf3097d40a025077caecb1cc181b62e2b991b703bb4c7f0350f3df1105112054d397a04ed0666ca4c804010582024e82054b616c7068610a626574610a1818818201506da3bb6071d750c9a949a41d80aeadd2181981835099f25f558f929e9517b51ebf3097d40a781e696e73706563742e61636365707465643e77726974655f66696c652e696e824e82816a77726974655f66696c658000 a80702116a77726974655f66696c6512824e82816a77726974655f66696c65800013676c3a737461727414801780181a5099f25f558f929e9517b51ebf3097d40a1822824382808000 a60703181b5099f25f558f929e9517b51ebf3097d40a181c6a77726974655f66696c65181e5820dc84b5f65453acf1d3d8b78ee597a5f8a263f6435219c95886187dbf6d97b09b181f011821781e696e73706563742e61636365707465643e77726974655f66696c652e696e a70703181b5099f25f558f929e9517b51ebf3097d40a181c6a77726974655f66696c65181e5820dc84b5f65453acf1d3d8b78ee597a5f8a263f6435219c95886187dbf6d97b09b181f02182082018182646578697482025082138269436f6d706c65746564820f801821781e696e73706563742e61636365707465643e77726974655f66696c652e696e a60702116a77726974655f66696c6512824e82816a77726974655f66696c6580001364703a696e148183781e696e73706563742e61636365707465643e77726974655f66696c652e696e824b828167696e7370656374800001178183646578697400a50150e4b73bb11bac0a9dfe97fefbc0202588025099f25f558f929e9517b51ebf3097d40a0350f3df1105112054d397a04ed0666ca4c804010582025082138269436f6d706c65746564820f80 seal 50b6357a920f562ed961f967f3fd8bc92b5e91b842e420393244291b24819721 ```
## Carry forward The guide explains the same source in [Types and expressions](/guide/02-types-and-expressions.md) and [Connectors and outcomes](/guide/03-connectors-and-outcomes.md). The Contract makes an effect reviewable: input, operation, bounds and outcomes travel together. Your application decides what to do with each result. A recording then lets you inspect what happened without repeating those effects. Previous: [Echo](/examples/01-echo.md). Next: [Two tenants](/examples/03-two-tenants.md), where the new question is who owns the state when several requests share a graph. ## Limits `max_read` bounds the complete input: no partial bytes are published on a read refusal. `File` does not implement recursive directory operations, append or watch. Atomic replacement concerns one target and depends on the Driver's supported filesystem boundary; refusals have typed outcomes. The `directory` Lab scenario scripts that result; the real File tests qualify the actual filesystem refusal. The example validates and copies bytes. --- --- title: Getting Started description: Install the current Rastok CLI, create a typed graph with a Lab scenario, and inspect a simulation without external services. url: https://docs.rastok.com/getting-started source_revision: v0.2.0-alpha --- # Getting Started You write `.rkg` programs. Rastok itself is written in Rust; you do not need Rust to use it. ## Install and run Rastok Rastok is currently in alpha. The release job builds binaries for **macOS Apple silicon** and **Linux x86-64**. Windows is not supported. The commands below install `v0.2.0-alpha` from its [release page](https://github.com/rastok-io/rastok/releases/tag/v0.2.0-alpha). Copy the command for your system below into a terminal. It downloads, verifies and installs Rastok. ### macOS Apple silicon For Macs with an Apple M-series chip, running macOS 11 or later: ```sh ( cd "$(mktemp -d)" && curl -fLO https://github.com/rastok-io/rastok/releases/download/v0.2.0-alpha/rastok-0.2.0-alpha-aarch64-apple-darwin.tar.gz && curl -fLO https://github.com/rastok-io/rastok/releases/download/v0.2.0-alpha/rastok-0.2.0-alpha-aarch64-apple-darwin.tar.gz.sha256 && shasum -a 256 -c rastok-0.2.0-alpha-aarch64-apple-darwin.tar.gz.sha256 && tar -xzf rastok-0.2.0-alpha-aarch64-apple-darwin.tar.gz rastok && mkdir -p "$HOME/.local/bin" && install -m 755 rastok "$HOME/.local/bin/rastok" ) && export PATH="$HOME/.local/bin:$PATH" && rastok --version ``` ### Linux x86-64 For 64-bit Intel or AMD systems with glibc 2.39 or later, such as Ubuntu 24.04. `uname -m` should report `x86_64`; `ldd --version` reports your glibc version. For Linux ARM64, older glibc or a system using musl, use the source installation below. ```sh ( cd "$(mktemp -d)" && curl -fLO https://github.com/rastok-io/rastok/releases/download/v0.2.0-alpha/rastok-0.2.0-alpha-x86_64-unknown-linux-gnu.tar.gz && curl -fLO https://github.com/rastok-io/rastok/releases/download/v0.2.0-alpha/rastok-0.2.0-alpha-x86_64-unknown-linux-gnu.tar.gz.sha256 && sha256sum -c rastok-0.2.0-alpha-x86_64-unknown-linux-gnu.tar.gz.sha256 && tar -xzf rastok-0.2.0-alpha-x86_64-unknown-linux-gnu.tar.gz rastok && mkdir -p "$HOME/.local/bin" && install -m 755 rastok "$HOME/.local/bin/rastok" ) && export PATH="$HOME/.local/bin:$PATH" && rastok --version ``` Each command installs `rastok` in `~/.local/bin` for your user account and prints `rastok 0.2.0-alpha`. To use it in new terminals, add `export PATH="$HOME/.local/bin:$PATH"` to your shell configuration: `~/.zshrc` for zsh (the macOS default), or `~/.bashrc` for bash. ### Other platforms and source builds
Installation and contribution instructions Rastok is written in Rust. You can compile it from source if your platform has no prebuilt binary, or if you prefer to build it yourself. First, follow the [official Rust installation instructions](https://rust-lang.org/tools/install/), including the build tools listed for your system. This also installs `rustup`, which selects the Rust version, and Cargo, which builds and installs Rust software. Open a new terminal and install the version used by Rastok: ```sh rustup toolchain install 1.97.1 ``` **Install the published release.** Cargo downloads the sources and dependencies, compiles them on your machine and installs the executable: ```sh cargo +1.97.1 install rastok --version 0.2.0-alpha --locked --features hosted-ui,hosted-websocket rastok --version ``` **Modify the source and contribute.** Clone the repository instead, then build and run your local copy. For a pull request, fork the repository on GitHub first and use your fork's URL in the clone command: ```sh git clone https://github.com/rastok-io/rastok.git cd rastok cargo +1.97.1 run --locked -p rastok --features hosted-ui,hosted-websocket -- --help ``` Cargo builds and runs the executable from your working copy. After editing, repeat this command or replace `--help` with the Rastok command you want to test. The [contribution guide](https://github.com/rastok-io/rastok/blob/main/CONTRIBUTING.md) explains the checks and review process for a pull request. Both installation routes include HTTP/1.1, HTTP/2, WebSocket and the debugger; HTTP/3 is not included.
### Create your first application In a directory for your work, run: ```sh rastok new hello rastok simulate hello.rkg --ui ``` Open the loopback URL printed by the last command, including its access token. The simulation starts paused. Choose **Next transition**, or **Finish** to reach `Hello, world`. The CLI reports `PASS hello.roundtrip_greeting` when the scenario finishes. Close the viewer from its toolbar when done. ### Get the examples Whether you installed Rastok from an archive or with `cargo install`, fetch the example sources and reference traces at the tag of your binary. This creates a `rastok-examples` checkout; it does not build or reinstall Rastok. Run these commands from the directory where you want to keep it (Git is required): ```sh git clone --depth 1 --branch v0.2.0-alpha https://github.com/rastok-io/rastok.git rastok-examples cd rastok-examples rastok simulate examples/echo.rkg ``` The simulation prints three `PASS` lines and `3 scenario(s), 0 failed`. If you already have a checkout at that tag, use it without cloning again. The [version policy](https://github.com/rastok-io/rastok/blob/main/README.md#versions) explains corrective releases, language changes and the independently numbered formats. ## The file `rastok new hello` writes The whole program, nineteen lines: one App graph with typed ports, one Operator with a handler, and a Lab with one scenario. No Connector, no external system. ```rkg graph hello : App { input in: string output out: string operator greet { input in: string output out: string on in { out = "Hello, " + data } } in -> greet -> out } lab hello { scenario roundtrip_greeting { app.in = "world" expect app.out == "Hello, world" } } ``` `rastok check hello.rkg` answers `ok: 2 node(s)` with the semantic hash; `rastok simulate hello.rkg` prints `PASS hello.roundtrip_greeting` and `1 scenario(s), 0 failed`. Start from this file rather than from the grammar; [Echo](/examples/01-echo.md) then adds a Connector, a mock and a recording. Debug: follow [The debugger, a guided tour](/debugger.md) for its controls, source view and assertion evidence. Without the browser, `rastok simulate hello.rkg` runs the same scenario. `rastok new` creates one file with a typed Operator and a Lab; it never overwrites an existing file. Change the source on disk, then run it again. Use `rastok --help` for the command syntax and `rastok --version` to identify your build. The [Command line chapter](/guide/09-command-line.md) explains all commands, options, output streams and exit statuses. From a checkout, continue with [echo](/examples/01-echo.md) for a real Process and an effect-free recorded replay. Then follow [webhook to partner](/examples/04-webhook-to-partner.md): its command supplies the synthetic deployment profile and can open the same graph with `--ui`. No real server, partner or credential is required for that simulation. `rastok run` prints each App output value on its own line when the App declares one output port. An App with several output ports prints `port: value` instead. Read [what `run` waits for](/guide/09-command-line.md#execute-the-app-run) before using it with a listening Connector or a pending deadline. Two unaided timed installation trials are still required before this quickstart is qualified. No elapsed-time claim is made yet. ## Editor support The 0.2.0-alpha release includes an installable syntax-highlighting package. Install it in VS Code with: ```sh curl -fLO https://github.com/rastok-io/rastok/releases/download/v0.2.0-alpha/rastok-dsl-0.2.0.vsix code --install-extension rastok-dsl-0.2.0.vsix ``` For VSCodium, use `codium --install-extension rastok-dsl-0.2.0.vsix`. The [editor instructions](https://github.com/rastok-io/rastok/blob/main/editors/vscode/rastok-dsl/README.md) explain how to package a local checkout; they also cover the JetBrains bundle. For Vim or Neovim, load the native runtime from the same checkout as the examples, following the [Vim and Neovim setup](https://github.com/rastok-io/rastok/blob/main/editors/vim/README.md). Emacs has a [native Rastok mode](https://github.com/rastok-io/rastok/blob/main/editors/emacs/README.md) loaded from that checkout as well. These integrations color source and detect `.rkg` files; they do not provide completion or type checking. `rastok check` validates the program. ## Three ways to learn Some people read the book first; others open an example and break it; others hand the first step to a coding assistant and read what it wrote. All three paths lead to the same place. Keep [Authoring rules](/reference/authoring-rules.md) open for common refusals, working alternatives and links to the corresponding Reference sections. - **By the book.** The [user guide](/guide/01-a-program.md) reads the language in order: a program, types and expressions, Connectors and outcomes, the Lab, running for real, instances, recurrence, data policy, then the command line and what to do when a partner's answer is lost. - **By example.** Eight examples, each built from a question, with a graph to read, a scenario to run, something to break and the first golden difference to read. - **With a coding assistant.** Open your preferred LLM harness or coding agent in an empty directory and give it a specification, for example: *"Using https://docs.rastok.com/llms.txt, develop a Rastok application and its Lab that meet the following specification: \."* The documentation tells it how to check and simulate what it wrote; read the result as you would read a colleague's: the compiler and the scenarios are the review. | Guide chapter | What it explains | |---|---| | [1. A program](/guide/01-a-program.md) | Graphs, Nodes, ports and wiring | | [2. Types and expressions](/guide/02-types-and-expressions.md) | Values and typed decisions | | [3. Connectors and outcomes](/guide/03-connectors-and-outcomes.md) | External boundaries and explicit dispositions | | [4. The Lab](/guide/04-the-lab.md) | Scenarios, mocks and golden comparisons | | [5. Running for real](/guide/05-running-for-real.md) | Deployment and diagnostic replay | | [6. Instances, state and time](/guide/06-instances-state-and-time.md) | Ownership, lifetimes and bounded waits | | [7. Loops and retries](/guide/07-loops-and-retries.md) | Finite progression and safe repetition | | [8. Privacy, secrets and measurements](/guide/08-privacy-secrets-and-measurements.md) | Data policy and original quantities | | [9. Command line](/guide/09-command-line.md) | Commands, options and exit statuses | | [10. When the answer is lost](/guide/10-when-the-answer-is-lost.md) | Distinguishing a lost reply from a refused operation | An Operator computes. A Connector is the only thing that touches the outside. [Echo](/examples/01-echo.md) shows both in one program. | Example | Your question | What you learn to keep explicit | |---|---|---| | [1. Echo: one graph, two worlds](/examples/01-echo.md) | Can I test a flow without starting its external program? | Computation, effects and the Lab | | [2. File pipeline: effects with a contract](/examples/02-file-pipeline.md) | What may this flow read or replace, and what happens when it cannot? | Bounded I/O and fault destinations | | [3. Two tenants: whose state is this?](/examples/03-two-tenants.md) | Can Alice retry while Bob is already done? | Instance ownership, finite retry and lifetime | | [4. Webhook to partner: put it together](/examples/04-webhook-to-partner.md) | Can I qualify an integration before the partner is available? | Admission, validation, deduplication, effects and audit | | [5. Sensor alarm: make time an input](/examples/05-sensor-alarm.md) | How do I test an absence, or a day of waiting? | Stateful decisions, timed joins and virtual time | | [6. Agent gateway: keep a conversation isolated](/examples/06-agent-gateway.md) | Can Alice and Bob share a graph without sharing a child process? | Resident Sessions, protocol adaptation and exact closure | | [7. Countdown: a bounded loop](/examples/07-countdown.md) | Can I prove that repeated work finishes? | Manager commands and a decreasing measure | | [8. HTTP model adapter](/examples/08-model-adapter.md) | What usage did the model actually report? | Typed responses, original measurements and absent versus zero | Chapter 6 connects WebSockets to resident Process Sessions: Alice and Bob keep distinct children and correctly addressed JSON replies. Chapter 8 sends independent HTTP jobs and inspects typed usage supplied by the model. A scripted answer exercises the adapter; it is not evidence of a real token bill. ## How to use the examples Read in order, or take the short route: [echo](/examples/01-echo.md), then [webhook to partner](/examples/04-webhook-to-partner.md). Every chapter runs independently from the checkout; no chapter requires files or state left by the previous one. Run the scenario, inspect the graph, make the suggested edit on disk, and read the first golden difference. Restore the edit before continuing. Keep a new scenario when you discover a useful failure: it becomes a check for your next revision. The debugger explains recorded execution; it does not edit the flow or fork an alternative world. By the end, the same ideas apply to a file, a partner API and an agent: who owns the state, where effects occur, what time means, and where each outcome goes. You do not need a different testing model for each integration. --- --- title: Types and expressions description: Follow typed payloads through guards, narrowing and pure expressions without confusing text, bytes or decoded JSON. url: https://docs.rastok.com/guide/02-types-and-expressions source_revision: v0.2.0-alpha --- # Types and expressions After this chapter you can read payload types and guarded transitions, distinguish business rejections from evaluation faults, and explain why decoded JSON still needs shape validation. ## Give the payload a shape A port carries an envelope: `data` holds its payload; `meta` holds provenance and application metadata. The payload has one resolved logical type, inferred before execution if the port declaration omits it. `type Name = ...` names a set of allowed values. `output out: Webhook` requires one of those values. See the [type reference](/reference/types.md). The webhook example names the shape it needs. This declaration is from `examples/webhook-to-partner.rkg`, lines 3–7: ```rkg type Webhook = struct { event_id: string email: string @personal(identifier = true) amount: int } ``` A `Webhook` requires two strings and a signed 32-bit integer. The annotation on `email` adds personal-data policy without changing its type. An assignment widens if every value fits: | From | Example destinations | |---|---| | `int` | `long`, `double`, `decimal` | | `uint` | `long`, `ulong`, `double`, `decimal` | | `long`, `ulong` | `decimal` | | `float` | `double` | | Peers | Common type | |---|---| | `u + 1`, unsigned `u` | `uint` | | `b ? i : l`, `int` and `long` arms | `long` | Use `data.d as? int` for a particular `double`: 7.0 gives 7; 7.5 gives null. See the [numeric reference](/reference/types.md#numeric-types). Named type declarations are structural aliases: their checked shape matters, not their name. Tagged-union case names remain part of the value. For `enum { Pending, Cancelled }`, write `out = Cancelled` where that enum is expected, or compare `data.status == Cancelled`. A conflicting variable name is refused. Types such as `FileExit` and `ProcessExit` come from the standard library; use them without copying their declarations or importing them. The [standard library reference](/reference/stdlib.md#types) lists these names. Modules and explicit imports remain a later design discussion. ## Test before projecting With `codec = json`, the webhook listener supplies a `variant`: a decoded value whose application shape is not yet known. An Operator cannot simply read arbitrary members of it. It first tests and narrows the value. The validation Operator, from the same file, lines 30–41, separates shape validation from the business rule: ```rkg operator validate { input in: variant output out: Webhook output failed: Failure on in match { data is Webhook => match { data.amount > 0 && size(data.event_id) > 0 => out = data as Webhook _ => failed = Rejected { reason = "positive amount and event id required" } } _ => failed = Rejected { reason = "expected event_id, email and integer amount" } } } ``` `is` asks whether the value fits a type or union case. On the successful branch, member access such as `data.amount` is checked with the narrower shape. `as` requests a conversion that succeeds only for a compatible value. The final `_` branch makes the alternative visible. These rejections emit `Rejected` on `failed`. A negative amount is a business outcome; malformed JSON is a Connector outcome. When `dossier: Open?` may be absent, use `dossier.?title.orValue("No dossier is open")`. A missing array element or map key gives null: `names[?i]`, `counts.?pending`. If the payload might not fit a type, `data as? Webhook` returns the value or null. A plain cast needs a proof, as in the successful branch above. A string can be tested directly: `subject.startsWith("RE:")` checks a prefix, `subject.contains("urgent")` a substring, and `filename.endsWith(".csv")` a suffix. All three return a boolean. ## Keep bytes and text distinct File reads produce `array`. Its inspection Operator, from `examples/file-pipeline.rkg`, lines 16–25, accepts only nonempty bytes: ```rkg operator inspect { input in: array output accepted: array output bytes_read: int output empty: bool on in match { size(data) > 0 => { bytes_read = size(data); accepted = data } _ => empty = true } } ``` The successful branch emits two values, in source order: a size and the unchanged bytes. The alternative emits a boolean and never sends bytes to the writer. `size` on bytes counts bytes. The example's UTF-8 scenario therefore counts three bytes for `é` followed by a newline, not two characters. Ports can carry timestamps, durations or null alone. `string(duration("5s"))` returns `"5s"`; `"id-" + string(42)` returns `"id-42"`. A typed [HttpClient response](/reference/connectors/http-client.md) decodes UTC timestamps. ## Understand the expression boundary Expressions are pure, deterministic and evaluated under bounds. They do not read a file, contact a server or obtain randomness. Guards such as Echo's `on in where data != ""` decide whether a handler runs; `match` selects an explicit branch inside the transition. Malformed dynamic text passed to `duration`, `timestamp` or `decimal` yields null; a malformed constant is refused at check. Division by zero still faults without committing a partial transaction or inventing an `err` output. The Lab runs the same expressions. The authorities are [`docs/spec/types.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/types.md), [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) and [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md). This chapter covers the executable examples, not every proposed frontend or codec. See [what is available today](/index.md#what-is-available-today) for the alpha limits. ## Summary - A resolved type is different from an external encoding. - `is` tests a shape; `as` performs a checked conversion. - Expected rejection is typed application data; evaluation faults are not implicit output ports. - Lab and App execute the same Operator expressions. ## Next Read [Connectors and outcomes](/guide/03-connectors-and-outcomes.md), then try [File pipeline](/examples/02-file-pipeline.md). Its empty and UTF-8 scenarios make the distinction between payload type and representation concrete. --- --- title: Process description: Ports, terminal outcomes, settings and qualification evidence for the Process connector. url: https://docs.rastok.com/reference/connectors/process source_revision: v0.2.0-alpha --- # Process `std/process@1`. `job` starts one child per Call and publishes its ordered frames with the exit. `service` opens a resident child per Node instance on first input and reuses it. One exit ends that child, not each application request. ## Declaration This declaration comes from `examples/echo.rkg`. Place the Connector in a Graph and wire its ports; the excerpt alone is not an App. ```rkg connector shell : Process { mode = job ; command = "cat" codec = lines idempotent = true; behavior = deterministic timeout = duration("5s") } ``` The [contract index](/reference/contracts.md) explains shared settings, build features and the distinction between a Contract, a Lab model and an installed Driver. Selector: `mode` defaults to `job`. In `job` mode, Calls on one instance are serialized and [queue time counts toward `timeout`](/reference/execution.md#instances-own-state-not-threads); `service` uses a Session instead. | Mode | Driver direction | Exchange | Lab model | Installed in this binary | |---|---|---|---|---| | `job` | outbound | call | `lab-call` | `process-job` | | `service` | inbound+outbound | session | `lab-process-service` | `process-service` | ## Ports and completion | Mode | Port | Direction | Type rule | |---|---|---|---| | job, service | `in` | input | `codec = lines` → `string`; `codec = jsonl` → `variant`; `codec = bytes` → `array` | | job, service | `out` | output | `codec = lines` → `string`; `codec = jsonl` → `variant`; `codec = bytes` → `array` | | job, service | `err` | output | `err_codec = lines` → `string`; `err_codec = bytes` → `array` | | job, service | `exit` | output | ProcessExit, below | | Mode | Output cardinality | |---|---| | job | `err`: zero or more; `out`: zero or more; exactly one final `exit` per Call | | service | Zero or more frames and writes; exactly one `exit` per Session | ## Exit union | Case | Payload | Call visibility | |---|---|---| | `CaptureFailed` | Empty | outcome_unknown | | `DecodeFailed` | `{ line: string?, message: string }` | outcome_unknown | | `Exited` | `{ exit_code: int, signal: int? }` | after_effect | | `OutcomeUnknown` | Empty | outcome_unknown | | `OutputOverflow` | `{ limit: ulong, reason: enum { Budget, Capacity } }` | outcome_unknown | | `SpawnFailed` | `{ message: string }` | before_effect | | `TimeoutExpired` | Empty | outcome_unknown | ## Settings With `codec = jsonl`, `rastok check` refuses a producer whose resolved type contains a [value without a JSON form](/reference/types.md#json-request-values), using `E-TYPE-INVALID`. A `variant` producer is checked at execution instead; an unencodable request produces `DecodeFailed` before its frame is written. In `service` mode, an unencodable request closes the Session. | Mode | Setting | Domain | Presence / default | Latest phase | |---|---|---|---|---| | job, service | `args` | `array` | `[]` | instance | | job, service | `behavior` | `deterministic \| probabilistic` | required | plan | | job, service | `codec` | `bytes \| jsonl \| lines` | required | plan | | job, service | `err_codec` | `bytes \| lines` | `lines` | plan | | job, service | `command` | `string` | required | instance | | job, service | `cwd` | `string` | optional | instance | | job, service | `env` | `map` | optional | instance | | job | `idempotent` | `bool` | `false` | plan | | job | `timeout` | `duration` | optional | instance | | job | `max_output` | `ByteSize` | `"8MiB"` | plan | | job | `on_timeout` | `kill` | `kill` | plan | | service | `max_frame` | `ByteSize` | `"1MiB"` | plan | The shared catalogue lists framing choices for both modes; service validation further restricts `codec` to `lines | jsonl` and `err_codec` to `lines`. Service has no per-turn timeout or idempotence setting. Its mock supports input-driven `match` responses and an optional terminal; delayed/unsolicited mock frames, `now()` in Session mocks and system-close acknowledgements are not scripted. Physical unsolicited output is supported. Job mocks retain the ordinary Call timeout and terminal rules. ## Qualification inventory `job`: fixture `crates/rastok/tests/conformance_process.rs`. Cases without a portable forced fixture: `CaptureFailed`, `OutcomeUnknown`. Related tests: `crates/rastok/tests/process_service.rs`, `crates/rastok/src/connector/drivers/process/mod.rs`. `service`: No dedicated full-Contract fixture is declared. Related tests: `crates/rastok/tests/process_service.rs`, `crates/rastok/src/connector/drivers/process/mod.rs`. --- --- title: Types and schemas description: Logical types, literal forms and the loss-checked JSON Schema, Avro, Arrow and OpenAPI projections shipped in the alpha. url: https://docs.rastok.com/reference/types source_revision: v0.2.0-alpha --- # Types and schemas Types describe values independently of their byte representation. A schema projection produces a Rastok type; it does not install a wire codec or a Driver. The [types chapter](/guide/02-types-and-expressions.md) introduces the notation. ## Scalars ### Numeric types Use the names in the first column in `.rkg` declarations. Their widths are fixed, not chosen by the machine. A computed value can enter another numeric type without a written conversion only when every value of its type fits. An annotation is the type you read back: `val seven: decimal = 7u` binds a `decimal`, while `val seven = 7u` binds a `uint`. | Source type | Representation and bounds | Computation in this alpha | |---|---|---| | `sbyte`, `short`, `int`, `long` | Signed 8-, 16-, 32- and 64-bit integers | Arithmetic, ordering and equality. Division truncates toward zero; carrier overflow and division by zero fault. A result must fit its destination. | | `byte`, `ushort`, `uint`, `ulong` | Unsigned 8-, 16-, 32- and 64-bit integers | Arithmetic, ordering and equality. Carrier overflow, underflow and division by zero fault. | | `half`, `float`, `double` | Binary16, binary32 and binary64 | Arithmetic at the result width, ordering and equality. Results can include infinities and NaN; ordering a NaN faults. | | `decimal` | Exact integer or decimal, not binary floating point | Carrying, schema projection, equality and explicit narrowing; no arithmetic or ordering | | `decimal(p,s)` | Exact decimal128 coefficient and scale; precision `1..38`, scale `-38..38` | Carrying, schema projection and equality; exact conversion from integers or `decimal`; no arithmetic or ordering, and narrowing never rounds | An unsigned literal chooses the first width that holds it: `7u` is `uint`, `4294967296u` is `ulong`. There is no separate `ulong` suffix. Write `int`, not `int32`, and `half`, not `float16`. Without context, a floating literal uses `double`. Where a `float` is expected, `0.1` and `4.099999904632568359375` both fit: the first keeps its displayed value, the second is exactly representable. A literal may also fit `double` by either rule and then fit `float` exactly: `0.10000000149011612` fits and displays `0.1`. Neither `0.1000000015` nor `0.123456789` fits. | Values that meet | Type used | |---|---| | `int` and `long` | `long` | | `int` and `double`, or `float` and `double` | `double` | | An integer and `decimal` | `decimal` | | An integer and `decimal(p,s)`, or two fixed decimals | The smallest fixed decimal that holds both, otherwise `decimal` | | `int` and `uint` | `long` | | `long` and `double`, `int` and `ulong`, or `float` and `decimal` | No common type; convert explicitly with `as?` | A `float` widened to `double` or carried as a `variant` keeps the value its shortest rendering denotes. Lists, map values and struct fields can widen when their contents can. The `%` result has the dividend's sign, including a negative zero. Floating remainder uses a quotient truncated toward zero. A zero divisor, infinite dividend or NaN operand yields NaN; a finite dividend modulo an infinite divisor is unchanged. Two declared decimals compare by value: `19.90` at scale two equals `19.900` at scale three. Each keeps its own scale for display. Two `decimal` values also compare by value: seven equals `decimal("7.00")`. Neither comparison rounds. `decimal` cannot be a map or instance key. See [numeric expressions](/reference/expressions.md#numeric-operands-in-this-alpha) for conversion examples and fault behavior. ### Other scalars | Type | Parameters and aliases | Value rule | |---|---|---| | `bool` | No parameter | `true` or `false` | | `null` | No parameter | The null value | | `string` | No parameter | Unicode text | | `array` | Variable length | Compact byte sequence; `size(b)` counts bytes and `b[?i]` returns a `byte?` | | `array` | Fixed length in source | Exactly `N` bytes; `1 <= N <= 2147483647` | | `uuid` | No parameter | Exactly 16 network-order bytes | | `string(max)` | Maximum length in Unicode scalar values | `"été"` fits `string(3)?`, and `["été"]` fits `array`. When the input may be longer, use `as? string(3)` and handle null. JSON Schema preserves `maxLength`; Avro and Arrow return `LossyProjection` at this field. | ## Dates, times and intervals Source declarations in this version accept only the bare names `date`, `time`, `timestamp`, `timestamp_ntz` and `duration`. They use the defaults below. Parameterized forms and calendar intervals belong to the logical model and transported schemas; they are not source type declarations. `interval` is not a built-in source type, either bare or parameterized. For logical `time`, `timestamp`, `timestamp_ntz` and `duration`, the unit is `second`, `millisecond`, `microsecond` or `nanosecond`. These parameterized temporal declarations are refused with `E-PARSE-DEFERRED`, naming the form. This does not affect value constructors such as `duration("2s")` or `timestamp("2026-10-30T12:00:00Z")`. | Logical type | Source default or logical parameters | Distinction preserved | |---|---|---| | `date(unit)` | `day` or `millisecond`; bare `date` means `day` | Date, carried as whole days | | `time(unit)` | Bare `time` means nanoseconds | Time of day, without a date | | `timestamp(unit, "zone")` | Bare `timestamp` means nanoseconds in UTC | Instant with a declared zone; `UTC`, `Etc/UTC` and `+00:00` normalize to UTC | | `timestamp_ntz(unit)` | Nanoseconds by default | Date and time without a zone; not UTC by omission | | `duration(unit)` | Nanoseconds by default | Signed elapsed quantity, carried in i64 nanoseconds | | `interval(year_month)` | Months | Calendar interval | | `interval(day_time)` | Days and time | Calendar interval with millisecond precision | | `interval(month_day_nano)` | Signed months, days and nanoseconds | Arrow interval constraints | | `interval(month_day_millis_unsigned)` | Unsigned 32-bit months, days and milliseconds | Avro duration constraints, distinct from the Arrow interval | Timestamp carriers contain signed i64 seconds and a nonnegative nanosecond fraction. The unit limits precision, not the seconds range. Arithmetic outside the carrier refuses. Logical execution time and civil timestamps are separate: `now()` observes the recorded origin plus the transaction's logical instant. ## Composite types `as? Record` checks the fields of either a struct or a JSON object against the declared record. For example, an unsigned seven can fill a `long` field; an unsigned value outside the `long` range makes the whole cast return null. | Form | Meaning | Constraints | |---|---|---| | `struct { name: string, count: int }` | Named fields | Closed, unique fields; declaration order is not type identity | | `array` | Ordered homogeneous sequence | Variable length | | `array` | Fixed sequence in the logical model only | Exactly `N` elements, including `N = 0`; source declarations refuse this form with `E-PARSE-DEFERRED` | | `map` | Homogeneous keyed collection | Canonical, non-null scalar or enum keys | | `enum { Ready, Done }` | Named unit cases | Write `Ready` or `Done` where this enum is expected, including a typed list element or opposite an enum operand of `==` or `!=`; a conflicting visible binding refuses | | `T?` | `T` or null | Absence and null are distinct at a boundary | | `A \| B` | Structural union | Branches must be pairwise disjoint; exactly one branch matches | | `union { Ok { value: string }, Refused }` | Tagged union | Named cases with closed payloads; the case remains part of the value | | `variant` | Self-describing value tree | Test its type with `is`. To read a schemaless JSON object as a declared struct, use `as? T` and handle null. | An optional enum `E?` resolves bare symbols wherever enum `E` does, including collection values and Lab assertions; a union with several non-null branches does not select an enum for a bare symbol. In the logical model, map keys admit booleans, fixed-width integers, strings, byte arrays, fixed-scale decimals, dates, times, timestamps, durations, UUIDs and enum symbols. Floats, `decimal`, null, intervals, dynamic values and composite keys refuse. Instance keys additionally admit closed structs of valid key leaves. Source map literals accept only string keys: `{ "id": "a" }` is a map, while `{ 1: "a" }` is refused. For `map`, `{"été": 1}` fits and `{"abcd": 1}` is refused at check. A non-string key type can still be declared, for example `map`, but only its empty literal `{:}` can be written in this version. Fixed-length arrays can be written only for `byte`. The `bytes` connector codec still names a wire format. Neither a byte array with a declared schema nor bytes carried in a `variant` have a JSON wire form. Named type declarations are structural aliases. Recursive aliases refuse. Type trees are bounded to 128 nesting levels, 4096 nodes and 256 members per aggregate. `type Name = @struct { ... }` declares a flat, annotation-capable struct; annotation use and interpretation are described in [Privacy, secrets and measurements](/guide/08-privacy-secrets-and-measurements.md). ## Standard types without imports The [standard library](/reference/stdlib.md#types) lists the named types available without imports, including `FileExit` and `ProcessExit`. They use the same definitions as the Connector ports, independently of the physical Drivers included in the binary. Write `output failed: FileExit` without copying its declaration; the library reference explains name collisions and the module and import design still to be discussed. ## Literals and constructors | Spelling | Result | Notes | |---|---|---| | `42`, `42u`, `1.5`, `true`, `null`, `"Ada"` | Intrinsic scalar | Ordinary expression literals retain their checked type | | `decimal("12.30")` | `decimal` carrying an exact decimal | A declared decimal target checks precision and rescales exactly | | `duration("2h30m")` | `duration` | Signed duration; units include `h`, `m`, `s`, `ms`, `us`, `ns` | | `{ room = "kitchen", celsius = 21 }` | Declared `struct` | Braced field assignments, `name = value`, checked against the struct type expected where the literal appears | | `[]`, `{:}` | Empty array, empty map | Use the expected type; without one, `array` and `map`; `{}` is an empty struct, not a map | | `timestamp("2026-10-30T12:00:00Z")` | `timestamp` | Parsed civil instant | | `json! { "count": 42 }` | `variant` | Also accepts scalar JSON. Duplicate keys and numbers without a lossless `long`, `ulong` or `double` representation refuse. | | `string! { message }` | `string` | Verbatim reader | | `base64! { SGk= }` | `array` | Standard base64, padding required; ASCII whitespace ignored | | `asset("fixtures/sample.pdf")` | `array` | Bytes read at build time and embedded in the plan | Tagged frontends occupy a complete value position. Bind their result before using it inside a larger expression. See [Expressions and dispatch](/reference/expressions.md). Without an expected type, `val members = []` infers `array` and `val counts = {:}` infers `map`. The same rule applies to `{ items = [] }`. A destination requiring more precise elements refuses such a binding with `E-PORT-TYPE`; annotate the declaration instead: `val members: array = []` or `var counts: map = {:}`. With elements, `val members = ["alice"]` infers `array`; mixed elements such as `[1, "a"]` infer `array`. The type belongs on the declaration: there is no `array []` value prefix. A typed list checks each element against its declared element type, as a typed map does for its values. With `data: string`, write `val names: array = [null, data]`. Without that expected type, `[null, "a"]` still infers `array`. An optional map keeps the same value context: for `map?`, `{ "a": null, "b": 1 }` constructs the optional values before the optional map. Likewise, an enum symbol resolves inside an optional collection: with `Status = enum { Pending, Done }`, write `[Pending]` for `array?` or `{ "x": Done }` for `map?`. A union with several non-null branches does not choose a collection branch for a bare symbol. ## JSON request values A JSON-encoding Connector input refuses a known producer type containing `array`, `duration`, `timestamp`, `date`, `time`, `timestamp_ntz`, `interval`, `uuid`, a map with non-string keys, or a tagged union, at any depth. `E-TYPE-INVALID` names the input and the first offending field. Convert the value explicitly before sending it. Enum symbols, exact decimals, finite floats, optional fields and maps with string keys have JSON forms. A `variant` producer passes this static check; a JSON value can be forwarded directly to another JSON Connector. Its value remains subject to the runtime encoder. A `variant` field does not hide a known non-JSON field elsewhere in the producer type. See the individual [Contracts](/reference/contracts.md) for their runtime refusals. Response decoding is a separate constraint: an encodable request type is not necessarily an admitted JSON response type. ## Schema projection rules The schema projection adapters report a path and a named loss reason. Reverse projection succeeds only when projecting the result back preserves the logical type. Source field order, physical union indexes and layout do not become type identity. | Refusal | Meaning | |---|---| | `UnsupportedSource` | Construct outside the admitted source subset | | `UnsupportedTarget` | No exact representation in the selected target | | `InvalidSchema` | Invalid schema or invalid parameters | | `RecursiveSchema` | Reference cycle | | `LossyProjection` | Conversion would discard a constraint or distinction | | `AmbiguousUnion` | Overlapping branches | | `InvalidMapKey` | Key outside the canonical-key domain | | `BudgetExceeded` | Resolved type exceeds a type-tree bound | A declared `decimal`, `decimal(p,s)`, `long` or `ulong` field also accepts a JSON string that spells an exact number in range. For example, the string `"9007199254740993"` enters a `long` unchanged; `"01"` is not a valid JSON number. Output uses an unquoted number. ### JSON Schema 2020-12 | Source or direction | Projection or refusal | |---|---| | `null`, `boolean`, `string`, `number`, `integer` | `null`, `bool`, `string`, `double`, `long` | | Integer with inclusive bounds exactly matching a machine width | Corresponding signed or unsigned integer | | Integer range `0..10` | `LossyProjection`, rather than widening to a machine integer | | String enum; homogeneous array; equal `minItems` and `maxItems` | Enum; variable array; fixed array | | Required named properties and `additionalProperties: false` | Closed struct | | Schema-valued additional properties without named fields | `map` | | Null plus one type; disjoint `oneOf` | Optional; structural union | | Optional property without a fill policy; required key on a map | `LossyProjection` | | Boolean schema, `pattern`, conditional constraints, tuple prefixes | `UnsupportedSource` | | Cyclic local reference; overlapping `oneOf` | `RecursiveSchema`; `AmbiguousUnion` | | Invalid definition or empty type array | `InvalidSchema` | | Reverse bytes, decimal scale, time units or tagged discriminants without an extension profile | `UnsupportedTarget` | ### Avro 1.12 | Source or direction | Projection or refusal | |---|---| | Null, boolean, int, long, float, double, bytes, string | Matching types; Avro bytes gives `array` and integers retain 32/64-bit widths | | Fixed, record, array, string-keyed map, enum | `array`, closed struct, array, string-keyed map, enum | | Decimal logical type | Decimal128, precision up to 38, `0 <= scale <= precision`; fixed storage must fit | | Date, time, timestamp and local-timestamp logical types | Matching date/time constructors, including zone-free timestamps | | Duration; UUID | `interval(month_day_millis_unsigned)`; `uuid` | | Disjoint union branches | Structural union with an explicit branch-index mapping | | Same-shape named record branches | Tagged union using resolved names | | Recursive record | `RecursiveSchema` | | Precision 39 or unknown logical type | `UnsupportedSource` | | Insufficient fixed decimal storage, forward undefined name or duplicate underlying union branch | `InvalidSchema` | | Reverse type without an exact Avro form | `UnsupportedTarget` or `LossyProjection` | ### Arrow | Source or direction | Projection or refusal | |---|---| | Integers, floats, decimal128 | Width, sign, precision and signed scale preserved | | Binary, large binary, binary view; UTF-8 variants | `array`; `string` | | Fixed binary; list variants; fixed list | `array`; variable array; fixed array | | Date, time, timestamp, duration, interval | Unit and zone preserved | | Struct, nullable field, map | Closed struct, optional field, canonical-key map | | Dictionary or run-end encoding | Decoded logical value type | | Dense or sparse union | Tagged union with explicit child-name/type-code mapping | | Extension type, decimal32/64/256 or out-of-range scale | `UnsupportedSource` | | Nullable or unsupported map key | `InvalidMapKey` | | Duplicate union type codes or child names | `InvalidSchema` | | Reverse tagged union with 129 cases | `UnsupportedTarget`: the flat target union cannot address that many children | ### OpenAPI 3.0 and 3.1 `rastok --resolve-open-api [--check]` discovers static HTTP endpoints and generates `openapi.generated.rkg`. It leaves authored sources untouched. `--check` reports a missing or stale generated file without writing. | Source | Projection or refusal | |---|---| | Local component reference | Expanded alias; cycles give `RecursiveSchema` | | 3.0 `nullable: true`; 3.1 type array with null | `T?` | | Integer format `int32` or `int64` | `int` or `long`, respectively; unbounded integer gives `LossyProjection` | | Number, number format float/double | `decimal`, `float` or `double`, respectively | | String, uuid, date, date-time, binary/byte, media-type formats | `string`, `uuid`, `date`, `timestamp`, `array`, `string`, respectively | | Fully required closed object; pure additional-property map | Closed struct; `map` | | Disjoint `oneOf` | Structural union | | Optional fields, open/mixed object or required map keys | `LossyProjection` | | Unknown format, discriminator, `readOnly` or `writeOnly` | `UnsupportedSource` | | Dynamic endpoint, no matching document or ambiguous document | Resolver refusal; no guessed endpoint | | Component name that is a standard type name | `UnrepresentableName`; no conflicting declaration is written | The HttpClient `json_profile = projected` setting is a separate boundary policy: it can skip extra fields and fill omitted nullable fields with null. It still rejects a wrong type or missing required field. It does not widen the OpenAPI schema projection above. ## Specified, not shipped | Item | Specification | |---|---| | Registered extension profiles for projections that need additional schema vocabulary | [`docs/spec/schema-projections.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/schema-projections.md) §§1–4 | | Decoder availability resolved through an attested registry | [`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md) §5.1 | Sources: [`docs/spec/types.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/types.md), [`docs/spec/schema-projections.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/schema-projections.md); executable projection evidence in `crates/rastok/tests/schema_projections.rs` and the OpenAPI projection/resolver tests. Runtime wire support remains specific to each [Contract](/reference/contracts.md). --- --- title: The debugger, a guided tour description: Read a simulation or a recorded execution through its source, transitions, envelopes and assertions. url: https://docs.rastok.com/debugger source_revision: v0.2.0-alpha --- # The debugger, a guided tour The debugger shows the program beside its recorded execution. Select a transition to see the source, the graph and the inspector at the same point. This tour uses the [webhook example](/examples/04-webhook-to-partner.md): a partner request times out, Retry schedules another attempt, and that attempt succeeds. ## Open the debugger Install a binary built with `hosted-ui`, then open a scenario: ```sh rastok simulate hello.rkg --ui ``` Use the `hello.rkg` created in [Getting Started](/getting-started.md), or supply the path of your program. The [webhook example](/examples/04-webhook-to-partner.md#run) gives the complete command and deployment profile for the graph in the tour. For an existing recording, use: ```sh rastok replay echo.rkr --ui ``` The CLI prints a loopback URL. Open that exact URL in your browser; it contains the capability needed to access this debugger. Keep it private. The URL is clickable in terminals that support hyperlinks. Leave the process running while you inspect it. `--ui-port` selects a port when you need one; otherwise the operating system chooses it. In Terminal on macOS, hold Command and double-click the URL to open it, as listed in the [Terminal keyboard shortcuts](https://support.apple.com/guide/terminal/trmlshtcts/mac). Other terminals may use a different shortcut. Copying the complete URL into your browser also works; do not omit its access token or share it. Simulation starts paused and can execute its Lab scenario. Diagnostic replay reads an existing recording without repeating external effects. These are different modes of the same interface, not two names for the Play button. ## Find your way around The numbered view is a recorded backoff transition of `webhook.timeout_then_success`. The numbers were added to the running page before capture; the state and values come from that scenario. The graph is shown at Readable size, centered on the Node of that transition; Fit graph shows the complete drawing instead. ![Numbered debugger regions at the webhook retry backoff](/assets/debugger-overview.png) 1. **App bar and mode.** The mode and execution status distinguish a live simulation, recorded history and diagnostic replay. 2. **Transport.** Back, Next transition, Next action, Run to expect, Finish, Play, Speed and Reset control which transition you see. The table below explains their differences. 3. **Timeline.** Select an already recorded transition or a simulation session. Return live goes back to the current execution head. Pending lists recorded obligations such as a retry deadline. 4. **Source.** File tabs, line numbers, the current marker and Search connect execution to the authored program. A selected graph element highlights its definition. Fold regions to keep the relevant part visible. 5. **Inspector.** Envelope shows data and metadata; Mailbox shows queued deliveries; Instances shows state and lifetime information; History shows recorded changes; Assertion explains an expectation; Compare aligns two instances or sessions for inspection. 6. **Graph and legend.** Nodes and connections show the selected transition. Select a node or a port to inspect it. The legend explains the visual notation; Fit and zoom change the view, not execution. 7. **Logical clock and controller.** The clock is the execution's logical time, not elapsed browser time. The controller role identifies the browser allowed to advance execution; another connected browser can inspect it. ## Advance deliberately | Control | What it does | |---|---| | Back | Select the preceding recorded transition. | | Next transition | Advance one recorded transition, executing when at the live head. | | Next action | In simulation, advance one authored scenario action to its effect. | | Run to expect | In simulation, continue to the next expectation. | | Finish | Continue to completion. | | Play / Pause | Advance through transitions at the selected playback speed, or stop. | | Speed | Choose the playback rate; it does not change logical deadlines. | | Reset | Start a clean simulation session for the selected scenario. | Selecting history does not undo a real external effect. Play is a playback control; `rastok replay` is the CLI command that opens a recording without Driver I/O. Controls that do not apply in the current mode are unavailable. ## Follow an identifier Hover an identifier in the source, or focus it with the keyboard, to read its recorded summary. When available, its link opens the corresponding inspector tab. Classified values and secret bindings stay redacted. ![An identifier summary in the generated starter program](/assets/debugger-hover.png) Selecting `greet` in the graph highlights its source definition. Source and graph are two views of the same selected transition. ![The selected greet Operator highlighted in the source](/assets/debugger-selection.png) ## Understand an assertion In the starter, change only `app.in = "world"` to `app.in = "monde"`, leaving the expectation unchanged. Open the changed program and choose Finish. The header shows the Lab's verdict. A pass includes the number of expectations; on failure, click the first failed expectation to open its recorded transition in Assertion. It may not be the last action. If only the reference trace differs, the header reports that instead: no expectation failed. Return live takes you back to the completed scenario. The Assertion tab shows the authored expectation, its observation window and the observed value beside the expected value. Here the Operator produced `"Hello, monde"`, not `"Hello, world"`. ![The starter assertion shows Hello, monde against Hello, world](/assets/debugger-assertion.png) An expectation inspects observations since the preceding injection or time advance. Successive expectations can inspect the same window. The debugger does not infer a missing observation or invent a comparison when a predicate cannot be explained field by field. ## Keyboard shortcuts | Key | Action | |---|---| | Left / Right | Select the preceding or following transition. | | `n` or F10 | Next transition. | | `a` | Next authored action. | | Space or F8 | Play / Pause. | | Enter | Open the selected envelope. | | Escape | Dismiss an overlay or selection. | | `/` | Search for a node, port or id. | Tab moves between controls, source identifiers and graph elements. Inputs and tab controls keep their own keys. Function keys work when the browser delivers them to the page; Space and `n` provide alternatives. ## What you cannot edit here This is not a development environment. It is read-only: values, source and scenarios cannot be edited in the debugger in this version. Inputs come from the scenario source, and there are no breakpoints. Edit the `.rkg` file in your editor and restart the simulation to test a different program or input. Continue with [the Lab](/guide/04-the-lab.md), [journal and replay](/guide/05-running-for-real.md), or the [command-line reference](/guide/09-command-line.md). --- --- title: "Two tenants: whose state is this?" description: Watch Bob finish once while Alice alone times out, waits for backoff and retries in an isolated keyed instance. url: https://docs.rastok.com/examples/03-two-tenants source_revision: v0.2.0-alpha --- # Two tenants: whose state is this? In `examples/keyed-retry.rkg`, Bob's request completes while Alice's waits for a retry. The reference traces for this example are filed under `two-tenants`. A file pipeline is easy to follow one request at a time. What happens when Alice's partner stalls while Bob's request is ready? This chapter adds instance ownership and finite retry to the same graph-and-Lab model. The versioned goldens cover native Retry: the failed attempt remains visible in the journal, while only the final outcome reaches the graph. The [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for the program and Lab, `.rkc` for a reviewed scenario reference and `.rkr` for a real execution recording. ## Run From the repository root, with `rastok` installed: ```sh rastok simulate examples/keyed-retry.rkg --compare examples/traces/two-tenants ``` ```text PASS ui_tour.two_tenants PASS ui_tour.lifetime 2 scenario(s), 0 failed ``` Add `--ui` to follow the same checked scenario in the debugger. ```sh rastok simulate examples/keyed-retry.rkg --compare examples/traces/two-tenants --ui ``` This requires `hosted-ui`. Open the private loopback URL printed by the CLI. For the controls and source view, see [the debugger tour](/debugger.md). ## Read the program The file starts with `type Request = struct { ... }`. This names a payload shape with two `string` fields, `tenant` and `prompt`; it does not create a request. `input in: Request` then uses that type on a port. The [type reference](/reference/types.md) explains structs and other type forms. Start with `instance = { key = data.tenant }`: it selects independent state for Alice and Bob. `Retry.attempts = 2` bounds Calls for one retained request, including the first; `lifetime` bounds how long an idle instance lives. They solve different problems. An instance is not a thread or a process. The current runtime executes Operator transactions one at a time, but an outstanding external Call does not prevent another instance from progressing. Bob can finish while Alice waits; this does not demonstrate parallel Operator execution. See [Instances, state and time](/guide/06-instances-state-and-time.md) for ownership and lifetime, and [Execution and concurrency](/reference/execution.md) for the current runtime and the planned worker pool. Then read `model : Process + Retry`, using the [Process contract](/reference/connectors/process.md): `Retry.on = [TimeoutExpired]` selects the terminal that permits another attempt. Retry retains the original request across attempts. `answer` decodes the final Process frame after the Retry manager has selected it. The nested `audit` Graph composes another branch. The [Lab reference](/reference/lab.md) explains mock responses, expectations and observation windows. `advance` supplies virtual time; a mock's terminal response ends its simulated exchange, not the whole scenario. Source: `examples/keyed-retry.rkg` ```rkg // Two tenants send requests: Bob finishes while Alice waits to retry. // The Lab checks that Alice's retry never starts a second request for Bob. type Request = struct { tenant: string prompt: string } type Answer = struct { tenant: string prompt: string } graph agent_retry : App { input in: Request output done: Answer output failed: ProcessExit instance = { key = data.tenant } lifetime = { kind = idle; max = duration("10s") } closing = { drain_for = duration("1s"); settle_for = duration("1s") } graph audit { input in: Request operator observe { input in: Request output out: string on in { out = data.tenant } } in -> observe observe.out -> nothing } connector model : Process + Retry { mode = job command = "cat" codec = jsonl idempotent = true behavior = probabilistic timeout = duration("1s") max_output = "1 MiB" Retry.attempts = 2 Retry.on = [TimeoutExpired] Retry.delay = { kind = fixed; after = duration("1s") } } operator answer { input in: variant output out: Answer on in { val decoded = data as? Answer match { decoded is Answer => out = decoded _ => nothing } } } in -> { audit; model } model.out -> answer -> done model.err -> nothing model.exit -> match { Exited -> nothing CaptureFailed | DecodeFailed | OutcomeUnknown | OutputOverflow | SpawnFailed | TimeoutExpired -> failed } } lab ui_tour { mock model { on in where data is Request && data.tenant == "alice" && now() == timestamp("1970-01-01T00:00:00Z") { out = nothing } on in { out = data exit = Exited { exit_code = 0; signal = null } } } scenario two_tenants { app.in = { tenant = "alice"; prompt = "Explain causal replay" } expect app.done == nothing app.in = { tenant = "bob"; prompt = "Explain typed envelopes" } expect app.done where data.tenant == "bob" advance duration("1s") expect app.done == nothing expect model.in == nothing advance duration("1s") expect app.done where data.tenant == "alice" expect answer.in == { "tenant": "alice", "prompt": "Explain causal replay" } expect 0 model.in where data is Request && data.tenant == "bob" expect audit.observe.in == nothing expect 0 app.done where data.tenant == "bob" expect app.failed == nothing } scenario lifetime { app.in = { tenant = "bob"; prompt = "First generation" } expect app.done where data.prompt == "First generation" advance duration("10s") expect model.in == nothing app.in = { tenant = "bob"; prompt = "Next generation" } expect app.done where data.prompt == "Next generation" expect app.failed == nothing } } ``` ## Expected result This cut of `ui_tour.two_tenants` follows `model` and `answer`; the separate `audit.observe` branch runs once per input and is omitted here. ```mermaid sequenceDiagram participant lab as Lab: ui_tour.two_tenants participant app as agent_retry participant model as model: Process + Retry participant answer as answer lab->>app: in = Alice's request app->>model: Alice, attempt 1 model->>lab: Scripted Call: no response lab->>app: in = Bob's request app->>model: Bob, attempt 1 model->>lab: Scripted Call lab-->>model: Bob's data, then Exited(0) model->>answer: Bob's data answer-->>app: done = Bob's answer lab->>lab: advance 1s Note over model: Alice: TimeoutExpired is Held, not delivered lab->>lab: advance 1s model->>lab: Alice, attempt 2: the same request lab-->>model: Alice's data, then Exited(0) model->>answer: Alice's data answer-->>app: done = Alice's answer Note over model: No second Call for Bob ``` Alice enters first and waits. Bob enters a separate instance and finishes immediately. Advancing one second expires Alice's Call; the next second admits her retry, which finishes. Bob receives no second Call. The `lifetime` scenario advances through ten seconds of silence, then proves that a new admission uses a fresh instance generation. `⧉` counts instances. The Instances tab's Retry table shows Bob's one attempt and Alice's two distinct Calls. Alice's timeout is recorded as **Held**, not delivered to the `failed` output; the final attempt is **Published**. The audit runs once per incoming request, not again for an internal retry. ## Break it Change `Retry.attempts = 2` to `Retry.attempts = 1`. Alice can no longer be readmitted: her original `TimeoutExpired` reaches `failed`, and the assertion expecting Alice's answer fails. Bob still finishes once. There is no new `RetryExpired` error type. ```sh rastok simulate examples/keyed-retry.rkg --compare examples/traces/two-tenants ``` ```text FAIL ui_tour.two_tenants expect app.done where data.tenant == "alice" (keyed-retry.rkg:95) nothing observed where data.tenant == "alice" is false for 0 of 0 deliveries; count 0, expected 1 expect answer.in == { "tenant": "alice", "prompt": "Explain causal replay" } (keyed-retry.rkg:96) nothing observed expected 1 matching delivery on answer.in, but observed 0 golden divergence: record 6: retry_protocol(43) . parent_id(2)[0][4]; expected 98f50438c7e3285a…(32 bytes); got 639236b28503f36b…(32 bytes); cause: TRANSACTION "model" · trigger "l:retry" · cause_id f3df1105112054d3…(16 bytes) FAIL ui_tour.lifetime golden divergence: record 6: retry_protocol(43) . parent_id(2)[0][4]; expected 98f50438c7e3285a…(32 bytes); got 639236b28503f36b…(32 bytes); cause: TRANSACTION "model" · trigger "l:retry" · cause_id f3df1105112054d3…(16 bytes) 2 scenario(s), 2 failed ``` Restore the checked-in source (this discards your edits to this example): ```sh git checkout -- examples/keyed-retry.rkg ``` ## Read the golden difference Add `--compare examples/traces/two-tenants` to compare every record. The unedited example matches. After your edit, the CLI names the first difference and recorded context, which can precede the final missing answer. Restore the attempt bound afterward.
Inspect the raw sealed trace (.rkc) The versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence. Source: `examples/traces/two-tenants/ui_tour.two_tenants.rkc` ```rastok-trace a6070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582025833820f82826670726f6d70748206754578706c61696e2063617573616c207265706c6179826674656e616e74820665616c69636509636c61620a000b000d8282742e696e3e61756469742e6f6273657276652e696e82581e8282656175646974676f627365727665818380018207820665616c69636500826c2e696e3e6d6f64656c2e696e82568281656d6f64656c818380018207820665616c69636500 a7070211601282508280818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8 a80702116561756469741282568281656175646974818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282508280818380018207820665616c69636500 a80702116d61756469742e6f6273657276651282581e8282656175646974676f627365727665818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282568281656175646974818380018207820665616c69636500 a8070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282508280818380018207820665616c69636500 a60702116d61756469742e6f6273657276651282581e8282656175646974676f627365727665818380018207820665616c696365001364703a696e148183742e696e3e61756469742e6f6273657276652e696e82508280818380018207820665616c6963650001178183636f757400a50150242f04840e2b7276f46b18be463a760e0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820248820665616c696365 a8070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013676c3a726574727914801780181a50f3df1105112054d397a04ed0666ca4c8182ba10282870150961dad6a19ad6dc36464a3b337506d5c509046c8137b2b3d115dfb05d17181057962696e582098f50438c7e3285ad952d34f94123cf760a8e4f60f14f6ef9446ad9ccc373b1d6d7374642f70726f6365737340318450f3df1105112054d397a04ed0666ca4c8582001f21d03f134e24c78d89a02c40b1518042219fa5d32b5295521810e04bfc4d780f6850250961dad6a19ad6dc36464a3b337506d5c01a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582025833820f82826670726f6d70748206754578706c61696e2063617573616c207265706c6179826674656e616e74820665616c696365509046c8137b2b3d115dfb05d171810579 a70703181b50f3df1105112054d397a04ed0666ca4c8181c656d6f64656c181e582001f21d03f134e24c78d89a02c40b1518042219fa5d32b5295521810e04bfc4d7181f0118216c2e696e3e6d6f64656c2e696e182ba1018250961dad6a19ad6dc36464a3b337506d5c01 a6070108a40150e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd04010582025833820f82826670726f6d70748206774578706c61696e20747970656420656e76656c6f706573826674656e616e74820663626f6209636c61620a010b000d8282742e696e3e61756469742e6f6273657276652e696e82581c8282656175646974676f627365727665818380018207820663626f6200826c2e696e3e6d6f64656c2e696e82548281656d6f64656c818380018207820663626f6200 a70702116012824e8280818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd a80702116561756469741282548281656175646974818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd1822824e8280818380018207820663626f6200 a80702116d61756469742e6f6273657276651282581c8282656175646974676f627365727665818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd182282548281656175646974818380018207820663626f6200 a8070211656d6f64656c1282548281656d6f64656c818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd1822824e8280818380018207820663626f6200 a60702116d61756469742e6f6273657276651282581c8282656175646974676f627365727665818380018207820663626f62001364703a696e148183742e696e3e61756469742e6f6273657276652e696e824e8280818380018207820663626f620001178183636f757400a50150f98c7c092a53d6d1a7989ec1f6b52b630250e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd040105820246820663626f62 a8070211656d6f64656c1282548281656d6f64656c818380018207820663626f620013676c3a726574727914801780181a50e6c20d6146234b74a33da1c709e86efd182ba10282870150b1c68415b421d87951425a4853e66f5650a08358e94753b1beccc9a14b211f98ca62696e582098f50438c7e3285ad952d34f94123cf760a8e4f60f14f6ef9446ad9ccc373b1d6d7374642f70726f6365737340318450e6c20d6146234b74a33da1c709e86efd5820e2c35b0b29e096536129210ebbf03f76743c3c01adec1d83f308c8d62115d3ef80f6850250b1c68415b421d87951425a4853e66f5601a40150e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd04010582025833820f82826670726f6d70748206774578706c61696e20747970656420656e76656c6f706573826674656e616e74820663626f6250a08358e94753b1beccc9a14b211f98ca a70703181b50e6c20d6146234b74a33da1c709e86efd181c656d6f64656c181e5820e2c35b0b29e096536129210ebbf03f76743c3c01adec1d83f308c8d62115d3ef181f0118216c2e696e3e6d6f64656c2e696e182ba1018250b1c68415b421d87951425a4853e66f5601 a80703181b50e6c20d6146234b74a33da1c709e86efd181c656d6f64656c181e5820e2c35b0b29e096536129210ebbf03f76743c3c01adec1d83f308c8d62115d3ef181f02182082018282636f7574820258378210828282066670726f6d70748206774578706c61696e20747970656420656e76656c6f7065738282066674656e616e74820663626f628264657869748202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f618216c2e696e3e6d6f64656c2e696e182ba1018250b1c68415b421d87951425a4853e66f5601 a8070211656d6f64656c1282548281656d6f64656c818380018207820663626f62001364703a696e1481836c2e696e3e6d6f64656c2e696e824e8280818380018207820663626f620001178283636f757400a501502f3afb52c023c8407761929204189d5b0250e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd040105820258378210828282066670726f6d70748206774578706c61696e20747970656420656e76656c6f7065738282066674656e616e74820663626f6283646578697400a5015021e0d24451d2373d0490524464f3fd210250e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd0401058202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f618198183502f3afb52c023c8407761929204189d5b736d6f64656c2e6f75743e616e737765722e696e8255828166616e73776572818380018207820663626f6200182ba2018250b1c68415b421d87951425a4853e66f56010282850650b1c68415b421d87951425a4853e66f56015061c7816a4b547232f22e62ea101f1c6b82502f3afb52c023c8407761929204189d5b5021e0d24451d2373d0490524464f3fd21840750b1c68415b421d87951425a4853e66f560101 a807021166616e73776572128255828166616e73776572818380018207820663626f620013676c3a737461727414801780181a502f3afb52c023c8407761929204189d5b1822824e8280818380018207820663626f6200 a607021166616e73776572128255828166616e73776572818380018207820663626f62001364703a696e148183736d6f64656c2e6f75743e616e737765722e696e82548281656d6f64656c818380018207820663626f620001178183636f757400a501506057c95cde89e87685a95298350240f702502f3afb52c023c8407761929204189d5b0350e6c20d6146234b74a33da1c709e86efd04010582025833820f82826670726f6d70748206774578706c61696e20747970656420656e76656c6f706573826674656e616e74820663626f62 a9070318188182045048a92fbc727f4d7ed69005b9f745d4ce181b50f3df1105112054d397a04ed0666ca4c8181c656d6f64656c181e582001f21d03f134e24c78d89a02c40b1518042219fa5d32b5295521810e04bfc4d7181f021820810218216c2e696e3e6d6f64656c2e696e182ba1018250961dad6a19ad6dc36464a3b337506d5c01 a7070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013696c3a74696d656f75741481836c2e696e3e6d6f64656c2e696e82508280818380018207820665616c6963650001178183646578697400a50150d5b3406cdffd7e099c4c3694fd0293b90250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c80401058202558213826e54696d656f757445787069726564820f80182ba2018250961dad6a19ad6dc36464a3b337506d5c010281850350961dad6a19ad6dc36464a3b337506d5c015001c6fbc51564f0a3ccf04ad9bc0e8bb08150d5b3406cdffd7e099c4c3694fd0293b9 a8070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013676c3a726574727914801780181a50d5b3406cdffd7e099c4c3694fd0293b9182ba10282850450961dad6a19ad6dc36464a3b337506d5c015001c6fbc51564f0a3ccf04ad9bc0e8bb08150d5b3406cdffd7e099c4c3694fd0293b9850550961dad6a19ad6dc36464a3b337506d5c01025001c6fbc51564f0a3ccf04ad9bc0e8bb0 aa070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013676c3a72657472791480178018188182015003260119a3813e2ae8426b064bdc8699181981835048a92fbc727f4d7ed69005b9f745d4ce782a4072657472793a39363164616436613139616436646333363436346133623333373530366435633a696e82568281656d6f64656c818380018207820665616c69636500181a50d5b3406cdffd7e099c4c3694fd0293b9182ba10281850250961dad6a19ad6dc36464a3b337506d5c02a5015048a92fbc727f4d7ed69005b9f745d4ce0250d5b3406cdffd7e099c4c3694fd0293b90350f3df1105112054d397a04ed0666ca4c804010582025833820f82826670726f6d70748206754578706c61696e2063617573616c207265706c6179826674656e616e74820665616c6963655003260119a3813e2ae8426b064bdc8699 a70703181b5048a92fbc727f4d7ed69005b9f745d4ce181c656d6f64656c181e582001f21d03f134e24c78d89a02c40b1518042219fa5d32b5295521810e04bfc4d7181f011821782a4072657472793a39363164616436613139616436646333363436346133623333373530366435633a696e182ba1018250961dad6a19ad6dc36464a3b337506d5c02 a80703181b5048a92fbc727f4d7ed69005b9f745d4ce181c656d6f64656c181e582001f21d03f134e24c78d89a02c40b1518042219fa5d32b5295521810e04bfc4d7181f02182082018282636f7574820258378210828282066670726f6d70748206754578706c61696e2063617573616c207265706c61798282066674656e616e74820665616c6963658264657869748202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f61821782a4072657472793a39363164616436613139616436646333363436346133623333373530366435633a696e182ba1018250961dad6a19ad6dc36464a3b337506d5c02 a8070211656d6f64656c1282568281656d6f64656c818380018207820665616c696365001364703a696e148183782a4072657472793a39363164616436613139616436646333363436346133623333373530366435633a696e82568281656d6f64656c818380018207820665616c6963650001178283636f757400a501505c3c5de80a70aba7a6912e427b7718b0025048a92fbc727f4d7ed69005b9f745d4ce0350f3df1105112054d397a04ed0666ca4c8040105820258378210828282066670726f6d70748206754578706c61696e2063617573616c207265706c61798282066674656e616e74820665616c69636583646578697400a5015031ee0198f4f892c3e741eed100a13b98025048a92fbc727f4d7ed69005b9f745d4ce0350f3df1105112054d397a04ed0666ca4c80401058202582a82138266457869746564820f828269657869745f636f646582020082667369676e616c821382008207f618198183505c3c5de80a70aba7a6912e427b7718b0736d6f64656c2e6f75743e616e737765722e696e8257828166616e73776572818380018207820665616c69636500182ba2018250961dad6a19ad6dc36464a3b337506d5c020282850650961dad6a19ad6dc36464a3b337506d5c025090dcc4a4031912c5809a3209963216e082505c3c5de80a70aba7a6912e427b7718b05031ee0198f4f892c3e741eed100a13b98840750961dad6a19ad6dc36464a3b337506d5c0201 a807021166616e73776572128257828166616e73776572818380018207820665616c6963650013676c3a737461727414801780181a505c3c5de80a70aba7a6912e427b7718b0182282508280818380018207820665616c69636500 a607021166616e73776572128257828166616e73776572818380018207820665616c696365001364703a696e148183736d6f64656c2e6f75743e616e737765722e696e82568281656d6f64656c818380018207820665616c6963650001178183636f757400a501507e8bba5f41e34f6dd8c6326184317c3f02505c3c5de80a70aba7a6912e427b7718b00350f3df1105112054d397a04ed0666ca4c804010582025833820f82826670726f6d70748206754578706c61696e2063617573616c207265706c6179826674656e616e74820665616c696365 seal 1edd9d70d157cdac9a426e4b84934e0cd1b77792f9e23eba7cad434db11d358f ```
## Carry forward Ask two separate questions in every stateful flow: "whose state?" and "for how long?" A key answers the first, a lifetime the second. Neither alone means that a duplicate request will be ignored. The next chapter will make that policy an explicit piece of state. Previous: [File pipeline](/examples/02-file-pipeline.md). Next: [Webhook to partner](/examples/04-webhook-to-partner.md), combining these mechanisms into an integration you can qualify before its partner is ready. ## Limits The Process mock is stateless: the admitted request and explicit logical time select its reply. Only Alice's request at time zero is silent. No real language model or paid API is used. The instance key isolates state but does not guarantee deduplication or persistence across a deployment restart. The fixed backoff is one second. --- --- title: Connectors and outcomes description: Read a Connector Contract, choose a supported mode, and route data and terminal outcomes explicitly. url: https://docs.rastok.com/guide/03-connectors-and-outcomes source_revision: v0.2.0-alpha --- # Connectors and outcomes After this chapter you can distinguish a Connector declaration from its Driver, find the supported modes in your binary, and route both useful data and terminal outcomes. You can explain why admission, completion and business success are different facts. ## Ask the catalogue first Run this command from the checkout or an installed CLI: ```sh rastok connectors ``` It lists compiled capabilities without starting a Driver. Read the exact Contract id, mode, port types, required attributes, checker support, Lab support and installed implementations separately. A Contract known to the compiler does not imply that your binary includes its physical Driver. Likewise, listing a conformance fixture does not mean the command ran it. The executable standard families are Process, File, HttpClient, HttpServer, WebSocketClient and WebSocketServer. The catalogue also describes deferred families or modes. A File `watch` entry is not permission to use it today. The [current status](/index.md#what-is-available-today) remains the starting point for the alpha's limits. ## One Contract, different operations The reader in `examples/file-pipeline.rkg`, lines 10–15, declares one bounded operation per input: ```rkg connector read_file : File { mode = read path = data as string max_read = "64KiB" timeout = duration("2s") } ``` `path` is resolved for the invocation from its input. It is a logical path relative to the root supplied to the physical File Driver, not permission to read an arbitrary host path. That root is a resolution base, not a portable security sandbox. The read publishes the complete bytes or no `out` value; exceeding `max_read` produces `ReadLimitExceeded`. The writer, lines 26–30, selects another mode of the same Contract: ```rkg connector write_file : File { mode = replace path = "copy.txt" timeout = duration("2s") } ``` It consumes bytes and reports a terminal outcome. Replacement is atomic where the platform supports the promised operation; otherwise the result is `AtomicReplaceUnavailable`, not an in-place fallback. Atomic visibility does not promise crash durability. Directories are refused by name rather than traversed as an implicit collection of files. A mode resolves the operation's direction, exchange and port behavior. The physical Driver and the Lab model implement the same checked Contract. Simulation substitutes the external work while preserving request validation and the declared ports. Driver selection is a deployment choice. ## Data is not the terminal outcome For File `read`, `out` carries bytes and `exit` closes the Call. For File `replace`, successful `out` is impossible; completion is still reported on `exit`. Process uses `err` for stderr. HTTP Contracts have no implicit `err`. The names are conventions whose actual meaning comes from the resolved Contract, not three universal success and fault channels. The file Graph names each outcome on both exits. Here is the reader at lines 37–41: ```rkg read_file.exit -> match { Completed -> nothing AtomicReplaceUnavailable | InvalidPath | IoFailed | NotAFile | NotFound | OutcomeUnknown | PermissionDenied | ReadLimitExceeded | TimeoutExpired -> failed } ``` Successful terminals are deliberately discarded. Other cases cross the App's `failed` output. These emissions remain observable in the journal even when their destination is `nothing`. An invocation's `exit` does not stop the whole Node instance; an instance may serve further invocations. When joining a Call's body and `exit`, route every terminal that accompanies a body to that join. Otherwise a retained body can pair with another Call's terminal: `W-JOIN-UNPAIRED` warns about this. A streamed port cannot pair zero or more frames with one terminal. To isolate Calls, use a correlation key shared by the body and terminal of just that Call. Declare the joining Operator's lifetime and bound the join with `within` or `last`, with `expired` routed. A join bound neither separates Calls nor closes their instances. See [joins and expiry](/guide/06-instances-state-and-time.md). ## Admission is not business success The webhook listener, from `examples/webhook-to-partner.rkg`, lines 23–28, uses the default `ack` mode: ```rkg connector listener : HttpServer { listen = "127.0.0.1:8080" path = "/events" codec = json max_body = "16 KiB" } ``` A successful accepting commit precedes the HTTP 202 response. That response means admitted, not processed. Decoded but business-invalid data can then reach the validation Operator and be rejected. Malformed JSON refused before admission creates no invented graph Call or `exit` to assert on. A decoded Lab injection therefore cannot qualify the physical JSON decoder. For an outbound HttpClient, a usable decoded 500–599 response produces `ServerError` and a response body, not a transport fault. Other decoded statuses use `Completed`; the graph still decides which mean business success. An incompatible response body produces `DecodeFailed`. A timeout does not establish that the remote side did nothing. Before asking an outbound Driver to act, the runtime commits the operation's obligation. Its completion then returns through the typed boundary and journal. In this alpha that journal is in memory; ordering before an effect is not a claim of durable recovery after process loss. The normative descriptions are [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md), [`docs/spec/delivery-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/delivery-semantics.md) and [`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md). Checking rejects unknown settings, incompatible port types and missing possible-output destinations before execution. Real-world compliance still needs separate Driver and integration evidence. ## Summary - Contract, mode and physical implementation answer different questions. - Payload outputs and the terminal `exit` are independently typed. - Explicit dispositions account for every possible result. - Admission and a decoded HTTP response are not business success. ## Next Continue with [The Lab](/guide/04-the-lab.md). Use [File pipeline](/examples/02-file-pipeline.md) to inspect named file refusals, then [Webhook to partner](/examples/04-webhook-to-partner.md) to follow admission, validation and the partner's terminal outcome together. --- --- title: HttpClient description: Ports, terminal outcomes, settings and qualification evidence for the HttpClient connector. url: https://docs.rastok.com/reference/connectors/http-client source_revision: v0.2.0-alpha --- # HttpClient `std/http-client@1`. One HTTP request per Call. Usable response bodies include non-success statuses. Decoded 500–599 responses use `ServerError`; other final statuses use `Completed`. A body decoding fault takes precedence over status classification. ## Declaration For an `http://` URL, the default is HTTP/1.1. To contact a server that requires cleartext HTTP/2, set `versions = ["http/2"]`. An HTTPS URL continues to use the declared order. This declaration comes from `crates/rastok/src/lab.rs`. Place the Connector in a Graph and wire its ports; the excerpt alone is not an App. ```rkg connector network : HttpClient { url = "https://example.test/v1" timeout = duration("5s") codec = json idempotent = true; behavior = deterministic } ``` The [contract index](/reference/contracts.md) explains shared settings, build features and the distinction between a Contract, a Lab model and an installed Driver. Calls on one instance are serialized; [queue time counts toward `timeout`](/reference/execution.md#instances-own-state-not-threads). | Mode | Driver direction | Exchange | Lab model | Installed in this binary | |---|---|---|---|---| | No selector | outbound | call | `lab-call` | Not compiled | ## Ports and completion | Mode | Port | Direction | Type rule | |---|---|---|---| | all | `in` | input | `codec = bytes` → `array`; `codec = json` → `variant`; `codec = string` → `string` | | all | `out` | output | `codec = bytes` → `array`; `codec = json` → `variant`; `codec = string` → `string`; explicit JSON response type admitted | | all | `exit` | output | HttpClientExit, below | | Mode | Output cardinality | |---|---| | all | Status 204 or 205: `Completed` with no `out`. Other `Completed` and `ServerError`: one `out`. Every Call ends with one `exit`. | ## Exit union | Case | Payload | Call visibility | |---|---|---| | `BodyTooLarge` | `{ limit: ulong }` | outcome_unknown | | `Completed` | `{ status: int }` | after_effect | | `ConnectFailed` | Empty | before_effect | | `DecodeFailed` | `{ message: string }` | outcome_unknown | | `DnsFailed` | Empty | before_effect | | `OutcomeUnknown` | Empty | outcome_unknown | | `ProtocolFailed` | Empty | outcome_unknown | | `ServerError` | `{ status: int }` | after_effect | | `TimeoutExpired` | Empty | outcome_unknown | | `TlsFailed` | Empty | before_effect | ## Settings With `codec = json`, `rastok check` refuses a producer whose resolved type contains a [value without a JSON form](/reference/types.md#json-request-values), using `E-TYPE-INVALID`. A `variant` producer is checked at execution instead: an unencodable request ends the Call with `DecodeFailed` before it is sent. Its message names `in` and the required codec representation. The JSON input is a `variant`; its object keys are not declared field names. For a typed JSON **response**, a `timestamp` field reads a UTC string such as `"2026-01-05T08:30:00.25Z"`. A `timestamp?` also admits `null`. An invalid or offset date ends the Call with `DecodeFailed` and no `out` delivery. In a `data is DecodeFailed` branch, `data.message` identifies the response field and what it expected. If the body is not JSON it names `out` instead. The message contains neither the rejected value nor a peer-supplied map key. To inspect the original value, receive it as a string or leave the response untyped. A request URL can include a numeric identifier: `url = "https://example.test/jobs/" + string(data.id)`. The number becomes a string explicitly; the JSON request codec does not change. | Mode | Setting | Domain | Presence / default | Latest phase | |---|---|---|---|---| | all | `auth_bearer` | `string` | optional | invocation | | all | `behavior` | `deterministic \| probabilistic` | required | plan | | all | `codec` | `bytes \| json \| string` | required | plan | | all | `json_profile` | `projected` | optional | plan | | all | `idempotent` | `bool` | `false` | plan | | all | `headers` | `HTTP headers` | optional | invocation | | all | `custom_headers` | `map>` | optional | invocation | | all | `idempotency_key` | `string` | optional | invocation | | all | `max_body` | `ByteSize` | `"8MiB"` | plan | | all | `method` | `string` | `"GET"` | invocation | | all | `timeout` | `duration` | required | instance | | all | `tls_ca` | `array` | optional | instance | | all | `tls_certificate` | `array` | optional | instance | | all | `tls_private_key` | `array` | optional | instance | | all | `url` | `string` | required | invocation | | all | `versions` | `array` | `["http/3", "http/2", "http/1.1"]` | plan | | all | `zero_rtt` | `disabled` | `disabled` | plan | `codec = json` permits an explicit `output out: Response`. `json_profile = projected` additionally skips extra members and fills absent nullable fields, while rejecting malformed required values. `auth_bearer = secret(...)` and `url = env(...)` use the declared boot-reference seam even though the table lists each setting's latest general phase. Those references are resolved from deployment configuration at startup, not from an input envelope. There is no automatic redirect or Retry: the graph declares its Retry policy. ## Qualification inventory fixture `crates/rastok/tests/conformance_http_client.rs`. Cases without a portable forced fixture: `DnsFailed`, `OutcomeUnknown`. Related tests: `crates/rastok/src/connector/drivers/network/http_client.rs`. --- --- title: Expressions and dispatch description: Operator precedence, built-in functions, narrowing, transaction dispatch and envelope writes accepted by the compiler. url: https://docs.rastok.com/reference/expressions source_revision: v0.2.0-alpha --- # Expressions and dispatch An expression reads its declared inputs and returns a value. Dispatch selects the statements of an Operator transaction. Neither performs external I/O; Connectors own that boundary. ## Operators Rows are ordered from highest to lowest precedence. Parentheses select an explicit grouping. Operators at the same arithmetic or comparison level associate left to right; the conditional's false branch associates right. | Level | Syntax | Rule | |---|---|---| | Access and narrowing | `data.name`, `(flag ? left : right).name`, `items[index]`, `value as T` | A named or computed receiver exposes the same declared fields; indexes require a checked collection | | Unary | `!value`, `-value` | Boolean negation; numeric or duration negation | | Multiplication | `*`, `/`, `%` | Numeric operations in the operands' common integer or floating type | | Addition | `+`, `-` | Numeric operations in the common type, string concatenation, supported timestamp/duration arithmetic | | Comparison | `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`, `is T` | Equality, ordering, membership and type/case tests | | Conjunction | `a && b` | Short-circuits when `a` is false | | Disjunction | `a \|\| b` | Short-circuits when `a` is true | | Conditional | `test ? yes : no` | Evaluates only the selected branch | `"red" in ["red", "blue"]` is true: an array tests its elements. `"red" in {"color": "red"}` is false: a map tests its keys, so `"color" in {"color": "red"}` is true. Neither form introduces an iteration variable. An unsupported operand combination reports the written operator and types, for example `` `+` does not accept array and array ``. List concatenation with `+` is not available in this version. Optional element types appear as `array` in type refusals. For an optional input carrying null, `data == null` is true and `data != null` is false. Whole inputs, optional fields and state cells follow the same comparison rule, including in guards and conditionals. ### Numeric operands in this alpha The [numeric type table](/reference/types.md#numeric-types) lists source names, representations and the operations each family supports. A literal first tries the other operand's type. Otherwise both values need a common type: `int + double` computes in `double`, but `long + double` is refused because not every `long` fits. Arithmetic and ordering on `decimal` and `decimal(p,s)` are not defined. For money, compute in integer minor units (cents) and keep the exact decimal for carrying and projection. Each operation on two `float` values rounds its result to binary32 before the next operation. A `double` uses binary64. If `u` is a `uint` holding 7, `u == 7` is true and `3 < u` is true: the literal takes the other operand's integer type if it fits. The rule also applies across the arms of a conditional: for a `long` named `n`, `ready ? n : 1` and `ready ? 1 : n` both return a `long`. Comparing a calculated `int` or `long` with a `uint` uses `long`. A signed integer and an `ulong` have no common integer type. With `u: uint?`, `u == 7` still tests for seven; it is false when `u` is null. An `int` compares with a `double` as a `double`, and every integer compares with a `decimal` as a `decimal`. A `long` or `decimal` and a `double` have no common type. Use a checked conversion (`as?`) and handle absence to compare a particular value. In a `decimal` position, `(7u as decimal) == decimal("7.00")` is true. Lists, records, map values and Lab expectations use the same rule. Comparing does not change what you see: `string(decimal("7.0"))` returns `"7.0"` and `string(decimal("7.00"))` returns `"7.00"`. `value as T` with `T` a declared `decimal(p,s)` (for example `type Price = decimal(18,2)`) accepts an exact integer or `decimal` that fits. `7 as Price` produces exactly `7.00`; exceeding the declared precision or discarding non-zero digits is a narrowing fault, never rounding. A `decimal("…")` literal is itself a `decimal`, so a Lab expectation against a `Price` port can use `expect app.out == { b = decimal("2.50") as Price }`. Numbers carried by `variant` compare by value: a signed seven, an unsigned seven and an exact decimal `7.00` are equal. A binary floating value meets an exact number through its shortest decimal rendering, not a tolerance. For a JSON number in a `variant`, `as?` checks the carried value: seven converts to `double`, and 19.99 converts to `decimal(10,2)`. `is` tests the carrier and never performs the conversion. Integer overflow and integer division by zero are evaluation faults. An index, map key or narrowing that can fail refuses at check; `[?i]`, `.?k` and `as?` return an optional value to test or default. A fault commits no input consumption, state change or emission from that transaction. Expected domain rejection must be represented by an authored branch and output. Expressions are limited to 128 nesting levels. The serialized plan has a separate 256-level reader bound; nested values can reach it even when the expression itself fits. ## Functions and contextual references Empty collections use the type expected at their position. Without one, `[]` is `array` and `{:}` is `map`, including in a binding or an inferred struct field. A destination requiring more precise elements refuses that binding with `E-PORT-TYPE`: declare `val members: array = []` or `var counts: map = {:}`. Nonempty collections infer their type from their elements. Numeric elements meet at their common type; when the elements have no common type, they infer `variant`. `{}` is a struct, never an empty map. At a typed position, each list element and each map value is checked individually. For example, `[null, data]` fits `array` when `data` is `string`. A declared `array` can hold a whole decimal and a fraction even when their precisions do not fit in a single fixed decimal. The same rule applies to both arms of a conditional and to the present value and the fallback of `.orValue()`. Without an expected type, `[null, "a"]` remains `array`. `{:}` also works inside expressions: `size({:})` is `0`, and map values and list elements may contain an empty map. | Signature | Result | Availability and constraints | |---|---|---| | `s.contains(t)` | `bool` | Tests whether the string `t` occurs in the string `s` | | `s.startsWith(t)` | `bool` | Tests the exact prefix, including an empty one | | `s.endsWith(t)` | `bool` | Tests the exact suffix, without case folding | | `size(string \| array \| array \| map \| variant)` | `int` | Unicode character count for strings, byte count for byte arrays, entry count otherwise | | `has(object.member)` | `bool` | Final-member presence on a closed struct or string-keyed map; present null is true; only dotted selection | | `now()` | `timestamp` | One transaction-fixed civil instant, derived from the run origin and logical time; handler context only | | `duration(string)` | `duration?` for runtime text, `duration` for a valid constant | Units `h`, `m`, `s`, `ms`, `us`, `ns`, with an optional leading minus. Components can be combined and fractional, but each must resolve to whole nanoseconds. No `min`, `d` or `w`. | | `timestamp(string)` | `timestamp?` for runtime input | RFC 3339 UTC spelling ending in `Z`; an unsupported offset or invalid date yields null | | `decimal(string)` | `decimal?` for runtime input | Exact decimal at its written scale, with no binary-float conversion | | `string(x)` | `string` | Renders a string, bool, integer, exact number, float, UTC timestamp, duration or enum symbol. Narrow optional and variant values first. | | `asset(path)` or `asset(path, content_type)` | `array` | Build-time file contents; the second argument is for a whole-payload position and sets its content type | | `env(name)` | Boot reference | Admitted at the HttpClient URL setting, resolved by the deployment profile | | `secret(name)` | Boot reference | Admitted at HttpClient `auth_bearer`; no raw secret value in graph data | `duration("4.1ms")` and `duration("4100us")` are equal. A fraction such as `0.1ns` is refused at check for a constant and yields null for a runtime string. For all four string constructors a valid constant keeps the ordinary result type. A malformed constant is an error even inside a reaction. For a declared decimal type `Price`, use `decimal(string(x)) as? Price` to recover the same value and type. `env` and `secret` are references, not evaluator functions. Other sites refuse. `has` does not establish the value's type: use `is` before reading it as a number or another narrower type. The receiver still has to be evaluable. `now` has no arguments and is unavailable in keys, settings or boot values. ## Narrowing and dispatch | Form | Selection | Requirement | |---|---|---| | `value is T` | Tests a type or tagged case | A positive fact narrows the right side of `&&`, a conditional's true branch, a guarded handler or a guarded match arm; the narrowed value can be used directly, without repeating `as T`. Assigning its state cell or the cell containing its path ends the fact for subsequent statements, which see the declared type again | | `value as T` | Proven conversion | The types fit, a constant converts exactly, or an `is` or closed-case arm proves this path | | `value as? T` | Optional conversion | A mismatch returns null; an ambiguous or malformed discriminator is still a fault | | `rows[?i]`, `entries[?key]`, `entries.?name` | Optional lookup | Returns null for an absent receiver, an out-of-range index or a missing key | | `row.?name` | Optional struct field | The field must be declared; a null receiver gives null | | `result.orValue(default)` | Default for `T?` | Both numeric choices must fit a declared result type; otherwise their common type is inferred. The default runs only when the result is absent. For a `uint?`, `.orValue(3)` and `.orValue(3u)` are equivalent. | | `match value { Case => ... }` | Closed match | Tagged union, enum or bool; exhaustive, disjoint case sets. A single-case arm exposes the matched path's payload fields; the whole value keeps its case | | `match { predicate => ...; _ => ... }` | Ordered predicates | First true predicate wins; fallback is mandatory | | `on in where predicate { ... }` | Single-input filter | False consumes the input and emits nothing | | `on (a, b) where predicate ...` | Join candidate selection | False consumes nothing; bounded waiting is covered in [Instances, state and time](/guide/06-instances-state-and-time.md) | A positive `data is Line` branch can construct an output record with `{ id = data.id }`: the field keeps the type that `Line` declares. A dynamic string may be too long for `string(3)?`. Use `data as? string(3)` and handle null. For a narrower array element, check the element before constructing the array. With an `array?` destination, `data.c ? [1] : null` yields the declared list or null. The same rule applies to a map literal. Between numeric types, `as?` returns null if the value would change. A binary float is worth the number shown by its shortest rendering: `0.1 as? decimal` gives the exact number 0.1, while `7.5 as? int` gives null. A float also accepts an exactly representable value even if it displays fewer digits: `4.099999904632568359375 as float` displays `4.1`. A literal that fits `double` and whose resulting binary64 value is exact in `float` also fits: `0.10000000149011612 as float` displays `0.1`. A declared decimal can be the target directly: `n as? decimal(5,2)`. For a `map`, `m[?k]` returns the stored value or null. Use `(m[?k] as? string).orValue("missing")` if you need a string even when the key is missing or the stored value is not a string. A match is the final control form of its block or arm. Only pure `val` declarations precede it. Dispatch permits at most 32 nested decisions, including a single-port `where`. A `variant` must be narrowed before member or index access. A negative test or disjunction supplies no inferred positive type fact. Inside `Stored => { ... }`, a match on `data` permits `data.name` when `Stored` declares that field. `out = data` and `out = .` still emit the complete `Stored { ... }` value. Several cases in one arm do not expose case-specific fields. Assigning the matched state cell ends the selection. Later `is` tests can read paths narrowed by earlier tests, for example `data is Booked && data.receipt is Receipt && data.receipt.note is string`. Each test is evaluated only after the preceding tests succeed. After a type test, fields, indexes and `has` read the selected value of an input just as they read a state cell. This also applies after `val copy = data`. Copying or passing the value without reading its structure does not decode it; type tests and conversions still use its retained union branch. For a tagged union `Event` with cases `Opened` and `Closed`, an `Event?` value satisfies `value is Event` whenever either case is present. It satisfies `value is Opened` only for that case. Both tests are false for null. After a successful case test, its payload fields can be read. A struct assigned to a declared type also constructs any optional fields that the destination requires. You can bind an inferred struct first and then use it in a typed field or output; the original binding keeps its type. Route selection is separate: `source -> match { Case -> target }` chooses among declared destinations using a tag, enum or bool. Its arms contain destinations, not expressions. A simple route may coexist with a match, but duplicate destinations for one case refuse. ## Fan-out and emission The shipped fan-out is bounded by the graph and the selected match arm. There is no collection-iteration statement in that arm. | Form | Result | |---|---| | `source -> { left; right }` | One emitted envelope delivered along two declared edges | | `(left, right) = data` | Evaluate once, then emit a distinct ordered envelope on each output | | `(left, right) = (first, second)` | One value per named output, committed together | | `out = .` | Re-emit the exact single input envelope | | `out = nothing` or `nothing` | No emission | | `out = { count = 1 }` | New structured data, inherited metadata | | `out = { data = replacement, meta.app.label = "checked" }` | New payload plus explicit metadata writes | Emission order within each port and transaction contributes to identity. An edge fan-out does not duplicate the emission itself. Iteration over state uses [Loop](/guide/07-loops-and-retries.md), whose manager admits subsequent applications outside the spatial DAG. ## Envelope fields and bindings On a struct port, `out = { data = data; meta.app.tag = "copy" }` copies the input payload and sets metadata. A field named `data` inside a payload struct is written under the outer `data` root. | Surface | Read | Write | |---|---|---| | `data` | Payload of the current single input | Construct a new output payload or checked patch | | `meta.sys.id`, `parent_id`, `origin_id`, `graph_version` | Runtime identity and version fields | Runtime only, including in the Lab | | `meta.app.*` | A required read has the field type inferred from graph-authored writes; no cast is needed | Declared-by-use application metadata; conflicting types refuse | | `meta.ext.*` | Contract-declared boundary context | Declared fields only; the payload/content-type coupling remains enforced | | `instance.key` | Selected key of this owner, with fields for a struct key | Read-only in handlers, owner bindings and instance-bound settings; not in its own definition or an unkeyed child | | `Loop.state` | Envelope admitted to the current Loop application | Replaced through a manager command, not mutated directly | | `.data`, `.meta` | Named inputs in a join | Emissions select a named source explicitly | In this build a metadata leaf is a scalar (`int`, not `uint`; no duration or timestamp) or an array of scalars. The `app` and `ext` namespaces have prefix-free field names. Heavy or nested payload structures belong in `data`. A Lab cannot introduce application metadata fields absent from the production graph. `val name = value` is immutable and lexical. Unit/App constants can be referenced by Lab declarations; instance-level values can use that owner's key and enclosing immutable values. `var name: Type = value` is mutable Operator state for one instance generation. Its initial value is required, even when the type allows null. Inside a handler an assignment takes effect at once: later statements read the new value. The change is committed with the transaction; a faulted transaction keeps the previous value. Children do not inherit it. ## Tagged frontends | Form | Result | Boundary | |---|---|---| | `json! ` | `variant` | One complete JSON value; duplicate keys refuse. A number must fit `long`, `ulong` or `double` without loss. | | `string! { ... }` | `string` | Verbatim text, closing-delimiter margin, no interpolation | | `base64! { ... }` | `array` | Padded standard base64; whitespace ignored | The name and `!` are adjacent. A frontend fills a complete value position, not an expression atom. Bind its result before combining it with arithmetic. `base64!("image/png") { ... }` may also declare content type in a whole-payload position. ## Specified, not shipped | Item | Specification | |---|---| | Regular expression matching (`s.matches(pattern)`) | Not part of the three string predicates in D-2026-11-28-1 | | Per-item fan-out (`foreach` is reserved); `for item in` is not accepted | [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), reserved-keyword section | | Expression macros `exists`, `exists_one`, `all`, `map` and `filter` | [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), expression production; current subset in [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §1.1 | | Array concatenation with `+` | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §1.1; use a list literal for known elements. | | jq, SQL and additional registered guest-language implementations | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §§2–3 | | `map>` metadata leaves | [`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md) §0 | | Unit/App boot values using `env` or `secret` outside the declared settings | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §1 | Sources: [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md), [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), [`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md) and [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) §1.1. --- --- title: "Webhook to partner: put it together" description: Admit a webhook, validate and deduplicate it, then exercise bounded partner retries with privacy, secret and cost evidence. url: https://docs.rastok.com/examples/04-webhook-to-partner source_revision: v0.2.0-alpha --- # Webhook to partner: put it together This program accepts a webhook, rejects invalid or duplicate events and sends accepted events to a partner. You know how to replace an effect, route its outcomes and isolate state. Now use those ideas for a familiar integration: receive a webhook and deliver it to a partner that is not always available. Build the flow and its fault scenarios together, before you need a live partner environment. All six scenarios have versioned goldens. The captures below show native Retry retaining a failed attempt and publishing the final outcome. The [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for the program and Lab, `.rkc` for a reviewed scenario reference and `.rkr` for a real execution recording. ## Run From the repository root: ```sh env RASTOK_SHOWCASE_PARTNER_TOKEN=lab-only-not-a-credential \ RASTOK_SHOWCASE_PARTNER_TOKEN_VERSION=fixture-v1 \ rastok simulate examples/webhook-to-partner.rkg \ --deployment examples/webhook-to-partner.deployment.json \ --compare examples/traces/webhook-to-partner ``` ```text PASS webhook.nominal PASS webhook.timeout_then_success PASS webhook.partner_dead PASS webhook.duplicate PASS webhook.invalid_payload PASS webhook.http_500 6 scenario(s), 0 failed ``` Add `--ui` to inspect the same graph. ```sh env RASTOK_SHOWCASE_PARTNER_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_PARTNER_TOKEN_VERSION=fixture-v1 rastok simulate examples/webhook-to-partner.rkg --deployment examples/webhook-to-partner.deployment.json --compare examples/traces/webhook-to-partner --ui ``` This requires `hosted-ui`. Open the private loopback URL printed by the CLI. No HTTP listener, real partner or paid API is started. The value above is a **fictional fixture**, not a credential. For real deployments, supply secret material out of band, never in source, profile JSON or shell command text. The profile contains only its coordinate and version. The same Contract is used with a scripted or physical Driver. For the controls and source view, see [the debugger tour](/debugger.md). ## Read the program Follow the main path first: `listener`, an [HttpServer](/reference/connectors/http-server.md), admits, `validate` checks the business data, `deduplicate` owns a `seen` flag per event, and `deliver` contains the bounded partner retry. Open that scope to find `request`, `partner : HttpClient + Retry` ([HttpClient](/reference/connectors/http-client.md)) and `decide`. The response type `Receipt` annotates the charge where the Connector retains it, before any decision to hold or publish the attempt. `decide` classifies the final business outcome; it contains no retry logic. `var seen: bool = false` declares mutable state inside `deduplicate`. Each `data.event_id` selects an Operator instance with its own flag, initialized to `false` when that instance is created. The first event sets it to `true` and is forwarded; a later arrival with the same key reads that committed value and takes the duplicate branch. The assignment and emission commit together. This is not a global variable or durable deduplication: after the instance closes, a new generation starts with `false` again. See [Values and mutable state](/guide/06-instances-state-and-time.md#values-and-mutable-state) before changing the handler. The `deliver` Graph is also keyed by event id. Like `deduplicate`, it closes after five minutes without an admission. A Retry can finish within that window, but the App does not keep a delivery instance for every event forever. Then read the declarations that constrain the path: the idle lifetime, the partner's idempotency key, the exhaustive destinations, `@personal` and the secret reference. These are reviewable parts of the program and deployment, not separate conventions the reader must guess from the happy path. The [Lab reference](/reference/lab.md) explains mock responses, expectations and observation windows. `advance` supplies virtual time; a mock's terminal response ends its simulated exchange, not the whole scenario. Source: `examples/webhook-to-partner.rkg` ```rkg // A webhook acknowledges requests, skips repeat deliveries and retries a partner call. // The Lab supplies fictional requests and partner replies without opening a socket. type Webhook = struct { event_id: string email: string @personal(identifier = true) amount: int } type Delivered = struct { event_id: string, status: int } type Failure = union { Rejected { reason: string } PartnerFailed { event_id: string, terminal: HttpClientExit } } type Receipt = struct { charge: decimal(38,18) @measure(id = amount, unit = "USD") } type Charge = decimal(38,18) graph webhook_to_partner : App { output done: Delivered output failed: Failure output duplicate: string connector listener : HttpServer { listen = "127.0.0.1:8080" path = "/events" codec = json max_body = "16 KiB" } operator validate { input in: variant output out: Webhook output failed: Failure on in match { data is Webhook => match { data.amount > 0 && size(data.event_id) > 0 => out = data as Webhook _ => failed = Rejected { reason = "positive amount and event id required" } } _ => failed = Rejected { reason = "expected event_id, email and integer amount" } } } operator deduplicate { input in: Webhook output out: Webhook output duplicate: string instance = { key = data.event_id } lifetime = { kind = idle; max = duration("5m") } var seen: bool = false on in match { seen => duplicate = data.event_id _ => { seen = true out = data } } } graph deliver { input in: Webhook output done: Delivered output failed: Failure instance = { key = data.event_id } lifetime = { kind = idle; max = duration("5m") } closing = { drain_for = duration("1s"); settle_for = duration("1s") } operator request { input in: Webhook output out: variant on in { // JSON erases the field schema: retain personal-data policy on the // opaque body, while the non-personal event id remains a typed key. out = { data = data as variant meta.app.event_id = data.event_id } } } connector partner : HttpClient + Retry { url = env("PARTNER_URL") auth_bearer = secret("showcase/partner/token") method = "POST" codec = json output out: Receipt timeout = duration("1s") max_body = "16 KiB" idempotency_key = meta.app.event_id // Required partner contract: honour this key for the identical request. // This declaration does not prove that a real service honours that contract. idempotent = true behavior = deterministic Retry.attempts = 2 Retry.on = [ServerError, TimeoutExpired, DnsFailed, ConnectFailed] Retry.delay = { kind = fixed; after = duration("1s") } } operator decide { input in: HttpClientExit output done: Delivered output failed: Failure on in match { data is Completed && data.status >= 200 && data.status < 300 => done = { event_id = meta.app.event_id as string status = data.status } _ => failed = PartnerFailed { event_id = meta.app.event_id as string terminal = data } } } in -> request -> partner partner.out -> nothing // On a lost answer, decide keeps the terminal case in the failure it reports. partner.exit -> match { BodyTooLarge | DecodeFailed | OutcomeUnknown | ProtocolFailed | TimeoutExpired -> decide Completed | ConnectFailed | DnsFailed | ServerError | TlsFailed -> decide } decide.done -> done decide.failed -> failed } listener.out -> validate -> deduplicate -> deliver listener.exit -> nothing validate.failed -> failed deduplicate.duplicate -> duplicate deliver.done -> done deliver.failed -> failed } lab webhook { mock deliver.partner { on in where data is Webhook && data.event_id == "dead" { out = nothing } on in where data is Webhook && data.event_id == "retry" && now() == timestamp("1970-01-01T00:00:00Z") { out = nothing } on in where data is Webhook && data.event_id == "http-500" && now() == timestamp("1970-01-01T00:00:00Z") { out = { charge = decimal("0.01") as Charge } exit = ServerError { status = 500 } } on in { out = { charge = decimal("0.02") as Charge } exit = Completed { status = 201 } } } scenario nominal { listener.out = { event_id = "ok"; email = "alice@example.test"; amount = 12 } expect listener.exit == Completed { status = 202 } expect app.done == { event_id = "ok", status = 201 } expect deliver.partner.in expect deliver.partner.out where data.charge == (decimal("0.02") as Charge) expect app.failed == nothing } scenario timeout_then_success { listener.out = { event_id = "retry"; email = "alice@example.test"; amount = 12 } expect listener.exit == Completed { status = 202 } expect app.done == nothing advance duration("1s") expect deliver.partner.exit == TimeoutExpired {} expect deliver.partner.in == nothing expect deliver.decide.in == nothing advance duration("1s") expect deliver.decide.in where data is Completed expect app.done == { event_id = "retry", status = 201 } expect app.failed == nothing } scenario partner_dead { listener.out = { event_id = "dead"; email = "alice@example.test"; amount = 12 } advance duration("1s") advance duration("1s") advance duration("1s") expect app.failed where data is PartnerFailed expect app.done == nothing advance duration("10s") expect deliver.partner.in == nothing expect app.failed == nothing } scenario duplicate { listener.out = { event_id = "same"; email = "alice@example.test"; amount = 12 } expect app.done listener.out = { event_id = "same"; email = "alice@example.test"; amount = 12 } expect listener.exit == Completed { status = 202 } expect app.duplicate == "same" expect deliver.partner.in == nothing expect app.done == nothing advance duration("5m") listener.out = { event_id = "same"; email = "alice@example.test"; amount = 12 } expect app.done expect app.duplicate == nothing } scenario invalid_payload { listener.out = json! { "unexpected": true } expect listener.exit == Completed { status = 202 } expect app.failed where data is Rejected expect deliver.partner.in == nothing listener.out = { event_id = "invalid"; email = "alice@example.test"; amount = -1 } expect listener.exit == Completed { status = 202 } expect app.failed where data is Rejected expect deliver.partner.in == nothing } scenario http_500 { listener.out = { event_id = "http-500"; email = "alice@example.test"; amount = 12 } expect deliver.partner.exit == ServerError { status = 500 } expect deliver.partner.out where data.charge == (decimal("0.01") as Charge) expect deliver.decide.in == nothing expect app.done == nothing advance duration("1s") expect app.done == { event_id = "http-500", status = 201 } expect app.failed == nothing } } ``` ## Expected result In `webhook.nominal`, admission produces the ACK before business validation; the scripted partner then completes the first attempt. ```mermaid sequenceDiagram participant lab as Lab: webhook.nominal participant listener as listener: HttpServer participant validate as validate participant dedup as deduplicate participant request as deliver.request participant partner as deliver.partner: HttpClient + Retry participant decide as deliver.decide participant app as webhook_to_partner lab->>listener: Decoded request: event_id = ok Note over listener: Admission ACK: Completed(202), disposed to nothing listener->>validate: out = decoded payload validate->>dedup: out = validated Webhook dedup->>request: First event_id: set seen, forward request->>partner: Body and meta.app.event_id partner->>lab: Scripted POST with idempotency key lab-->>partner: Receipt charge 0.02 USD, then Completed(201) Note over partner: Receipt measured in journal, out disposed to nothing partner->>decide: exit = Completed(201) decide-->>app: done = event_id ok, status 201 ``` `6 scenario(s), 0 failed` covers: - `nominal`: one `202` ACK and one partner Call ending with `201`; - `timeout_then_success`: one second to timeout, one second of backoff, then success on the second attempt; - `partner_dead`: two timed-out Calls, then the final `TimeoutExpired` inside the business `PartnerFailed` response, with no further Call even after another ten seconds; - `duplicate`: an explicit `seen` state suppresses a second request with the same event id; after five minutes idle, a fresh instance admits it again; - `invalid_payload`: decoded JSON with the wrong shape, then a negative amount, both rejected after ACK and without contacting the partner; - `http_500`: `ServerError { status: 500 }` is a decoded response; the static `Retry.on` policy selects it, and the second response is `201`. The email field is `@personal`. The deployment must attest the in-memory processing before admission; having a valid secret binding alone is not enough. Debugger views redact before formatting. Personal data can remain in the in-memory causal journal: presentation masking is not erasure. The bearer is different: its clear bytes never enter the journal at all. The declared `output out: Receipt` interprets the fictional partner's `charge` field as an exact amount with `@measure(id = amount, unit = "USD")`. That declaration names a quantity and its unit, not a billing policy. No downstream accounting Operator is run or replayed to extract it. The nominal reply reports `0.02`; the `500` and successful replies retain two separate samples, `0.01` and `0.02`, with their causal references. The first is Held by Retry and never reaches `decide`; it remains inspectable in the journal. M1 computes no total or price and the debugger displays the original DATA, not a cost report. A timed-out Call supplies no charge: missing evidence is **unknown cost, not a zero bill**. ## Break it Change the single `Retry.attempts = 2` to `Retry.attempts = 1`. The timeout and `500` scenarios can no longer succeed on a second attempt. Run the comparison below. ```sh env RASTOK_SHOWCASE_PARTNER_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_PARTNER_TOKEN_VERSION=fixture-v1 rastok simulate examples/webhook-to-partner.rkg --deployment examples/webhook-to-partner.deployment.json --compare examples/traces/webhook-to-partner ``` ```text FAIL webhook.nominal golden divergence: record 12: retry_protocol(43) . parent_id(2)[0][4]; expected [REDACTED]; got [REDACTED]; cause: [REDACTED] FAIL webhook.timeout_then_success expect [REDACTED] (webhook-to-partner.rkg:167) observed: [REDACTED] Assertion evidence is redacted because this program carries classified data. expect [REDACTED] (webhook-to-partner.rkg:169) observed: [REDACTED] Assertion evidence is redacted because this program carries classified data. expect [REDACTED] (webhook-to-partner.rkg:170) observed: [REDACTED] Assertion evidence is redacted because this program carries classified data. golden divergence: record 12: retry_protocol(43) . parent_id(2)[0][4]; expected [REDACTED]; got [REDACTED]; cause: [REDACTED] FAIL webhook.partner_dead expect [REDACTED] (webhook-to-partner.rkg:179) observed: [REDACTED] Assertion evidence is redacted because this program carries classified data. golden divergence: record 12: retry_protocol(43) . parent_id(2)[0][4]; expected [REDACTED]; got [REDACTED]; cause: [REDACTED] FAIL webhook.duplicate golden divergence: record 12: retry_protocol(43) . parent_id(2)[0][4]; expected [REDACTED]; got [REDACTED]; cause: [REDACTED] PASS webhook.invalid_payload FAIL webhook.http_500 expect [REDACTED] (webhook-to-partner.rkg:215) observed: [REDACTED] Assertion evidence is redacted because this program carries classified data. expect [REDACTED] (webhook-to-partner.rkg:218) observed: [REDACTED] Assertion evidence is redacted because this program carries classified data. golden divergence: record 12: retry_protocol(43) . parent_id(2)[0][4]; expected [REDACTED]; got [REDACTED]; cause: [REDACTED] 6 scenario(s), 5 failed ``` Restore the checked-in source (this discards your edits to this example): ```sh git checkout -- examples/webhook-to-partner.rkg ``` ## Read the golden difference Add `--compare examples/traces/webhook-to-partner`. The CLI names the first differing record and field, expected versus actual, and recorded causal context. This classified graph deliberately redacts values in divergence messages. Recorded operation facts can differ before the final answer does. The versioned goldens contain **only the synthetic fixture data**; they are not sanitized exports suitable for real personal data. ### Why five attempts also fail this comparison `Retry.attempts` is a maximum including the first Call, not a promise that the partner eventually answers. The `partner_dead` mock stays silent on every attempt. Its scenario expects the final failure after two one-second timeouts and one second of backoff, then expects no further activity. With five attempts, the operation is still waiting at that first assertion: the additional attempts move the final failure into the later observation window. The scenario no longer describes the configured policy. There is a separate reason for a golden divergence. Retry facts record the original plan's semantic hash. Changing the attempt bound changes that hash, even in a scenario whose final business value stays the same. A golden comparison checks those facts, not just the last value on `app.done`. With `Retry.attempts = 5`, this command checks only the scenario assertions: ```sh env RASTOK_SHOWCASE_PARTNER_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_PARTNER_TOKEN_VERSION=fixture-v1 rastok simulate examples/webhook-to-partner.rkg --deployment examples/webhook-to-partner.deployment.json ``` ```text PASS webhook.nominal PASS webhook.timeout_then_success FAIL webhook.partner_dead expect [REDACTED] (webhook-to-partner.rkg:179) observed: [REDACTED] Assertion evidence is redacted because this program carries classified data. expect [REDACTED] (webhook-to-partner.rkg:183) observed: [REDACTED] Assertion evidence is redacted because this program carries classified data. PASS webhook.duplicate PASS webhook.invalid_payload PASS webhook.http_500 6 scenario(s), 1 failed ``` Adding `--compare examples/traces/webhook-to-partner` also detects changed Retry facts in every scenario that opens a partner operation. Restore the reviewed two-attempt policy after this experiment: ```sh git checkout -- examples/webhook-to-partner.rkg ``` If five attempts are an intended policy change, update the exhaustion scenario's time advances and expectations, review the changed journal, then save the new reference. Do not overwrite references just to remove a divergence. [Loops and retries](/guide/07-loops-and-retries.md) explains the attempt bound and closure-based delay. ### Inspect the recorded retry The following 30-second sequence visits recorded states of `webhook.timeout_then_success`: admission, timeout, backoff and successful second attempt. During the backoff, Retry retains the failed batch without delivering it to `decide`; only the final result is published. These are real debugger views of a simulation, not live HTTP requests or an edited branch. The graph is shown at Readable size, where the view follows the Node of each transition; Fit graph shows the complete drawing. ![Thirty seconds through the recorded timeout and retry transitions](/assets/webhook-tour.png) Three stills make the checkpoints easier to inspect: - [Before admission, transition 0](/assets/webhook-before.png). - [Retry backoff scheduled, transition 20](/assets/webhook-backoff.png). - [Success after two attempts, transition 34](/assets/webhook-completed.png).
Inspect the raw sealed trace (.rkc) The versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence. Source: `examples/traces/webhook-to-partner/webhook.nominal.rkc` ```rastok-trace a9070108a40150f09d9a552439b865d3e4c81c1d1153130350f09d9a552439b865d3e4c81c1d11531304010582025839820f838266616d6f756e7482020c8265656d61696c820672616c696365406578616d706c652e7465737482686576656e745f69648206626f6b09686c697374656e65720a000b000c636f75740d818278186c697374656e65722e6f75743e76616c69646174652e696e824c82816876616c696461746580000f81686c697374656e6572108250f09d9a552439b865d3e4c81c1d115313824c8281686c697374656e65728000 a7070211601282438280800013676c3a737461727414801780181a50f09d9a552439b865d3e4c81c1d115313 a8070211686c697374656e657212824c8281686c697374656e6572800013676c3a737461727414801780181a50f09d9a552439b865d3e4c81c1d1153131822824382808000 a80702116876616c696461746512824c82816876616c6964617465800013676c3a737461727414801780181a50f09d9a552439b865d3e4c81c1d1153131822824382808000 a8070211686c697374656e657212824c8281686c697374656e6572800013676c3a7265706c791480178183646578697400a501503fafcc12ed987e27f9b7b5d1f8f4478d0250f09d9a552439b865d3e4c81c1d1153130350f09d9a552439b865d3e4c81c1d1153130401058202581c82138269436f6d706c65746564820f818266737461747573820218ca181a50f09d9a552439b865d3e4c81c1d115313182650f09d9a552439b865d3e4c81c1d115313 a70702116876616c696461746512824c82816876616c696461746580001364703a696e14818378186c697374656e65722e6f75743e76616c69646174652e696e824c8281686c697374656e6572800001178183636f757400a5015017381d0576454a378d6103ff771e6d060250f09d9a552439b865d3e4c81c1d1153130350f09d9a552439b865d3e4c81c1d11531304010582025839820f838266616d6f756e7482020c8265656d61696c820672616c696365406578616d706c652e7465737482686576656e745f69648206626f6b181981835017381d0576454a378d6103ff771e6d06781b76616c69646174652e6f75743e64656475706c69636174652e696e82582582816b64656475706c69636174658183816b64656475706c69636174650182078206626f6b00 a80702116b64656475706c69636174651282582582816b64656475706c69636174658183816b64656475706c69636174650182078206626f6b0013676c3a737461727414801780181a5017381d0576454a378d6103ff771e6d061822824382808000 a80702116b64656475706c69636174651282582582816b64656475706c69636174658183816b64656475706c69636174650182078206626f6b001364703a696e148183781b76616c69646174652e6f75743e64656475706c69636174652e696e824c82816876616c6964617465800001168182647365656e8201f5178183636f757400a5015037374515af1bad8312f98b4daa42b538025017381d0576454a378d6103ff771e6d060350f09d9a552439b865d3e4c81c1d11531304010582025839820f838266616d6f756e7482020c8265656d61696c820672616c696365406578616d706c652e7465737482686576656e745f69648206626f6b181981835037374515af1bad8312f98b4daa42b538782264656475706c69636174652e6f75743e64656c697665722e726571756573742e696e82582582826764656c6976657267726571756573748183816764656c697665720182078206626f6b00 a80702116764656c697665721282581d82816764656c697665728183816764656c697665720182078206626f6b0013676c3a737461727414801780181a5037374515af1bad8312f98b4daa42b5381822824382808000 a80702116f64656c697665722e726571756573741282582582826764656c6976657267726571756573748183816764656c697665720182078206626f6b0013676c3a737461727414801780181a5037374515af1bad8312f98b4daa42b538182282581d82816764656c697665728183816764656c697665720182078206626f6b00 a80702116f64656c697665722e726571756573741282582582826764656c6976657267726571756573748183816764656c697665720182078206626f6b001364703a696e148183782264656475706c69636174652e6f75743e64656c697665722e726571756573742e696e82582582816b64656475706c69636174658183816b64656475706c69636174650182078206626f6b0001178183636f757400a601508123dbaa681417af92bf1d659477f59e025037374515af1bad8312f98b4daa42b5380350f09d9a552439b865d3e4c81c1d11531304010582025839820f838266616d6f756e7482020c8265656d61696c820672616c696365406578616d706c652e7465737482686576656e745f69648206626f6b06818363617070686576656e745f69648206626f6b181881820150f68b7eb0b2ef76045c336f9390debc9218198183508123dbaa681417af92bf1d659477f59e782664656c697665722e726571756573742e6f75743e64656c697665722e706172746e65722e696e82582582826764656c6976657267706172746e65728183816764656c697665720182078206626f6b00 a80702116f64656c697665722e706172746e65721282582582826764656c6976657267706172746e65728183816764656c697665720182078206626f6b0013676c3a737461727414801780181a508123dbaa681417af92bf1d659477f59e182282581d82816764656c697665728183816764656c697665720182078206626f6b00 a80702116f64656c697665722e706172746e65721282582582826764656c6976657267706172746e65728183816764656c697665720182078206626f6b0013676c3a726574727914801780181a508123dbaa681417af92bf1d659477f59e182ba10282870150c8fa3674c4ed0eab3192771f1392030850f68b7eb0b2ef76045c336f9390debc9262696e58204583fb2221dac2d4c535ef23eb79b2682fb02d8aafe91e8ace4e365738c854aa717374642f687474702d636c69656e74403184508123dbaa681417af92bf1d659477f59e58208c3c3e457b61b7ba324420aa9ea838dd5667bdbdb36420401e19becaab3ba2f281826f6964656d706f74656e63795f6b65798206626f6bf6850250c8fa3674c4ed0eab3192771f1392030801a601508123dbaa681417af92bf1d659477f59e025037374515af1bad8312f98b4daa42b5380350f09d9a552439b865d3e4c81c1d11531304010582025839820f838266616d6f756e7482020c8265656d61696c820672616c696365406578616d706c652e7465737482686576656e745f69648206626f6b06818363617070686576656e745f69648206626f6b50f68b7eb0b2ef76045c336f9390debc92 a70703181b508123dbaa681417af92bf1d659477f59e181c6f64656c697665722e706172746e6572181e58208c3c3e457b61b7ba324420aa9ea838dd5667bdbdb36420401e19becaab3ba2f2181f011821782664656c697665722e726571756573742e6f75743e64656c697665722e706172746e65722e696e182ba1018250c8fa3674c4ed0eab3192771f1392030801 a80703181b508123dbaa681417af92bf1d659477f59e181c6f64656c697665722e706172746e6572181e58208c3c3e457b61b7ba324420aa9ea838dd5667bdbdb36420401e19becaab3ba2f2181f02182082018282636f7574820257820f81826663686172676582088247470de4df820000128264657869748202581c82138269436f6d706c65746564820f818266737461747573820218c91821782664656c697665722e726571756573742e6f75743e64656c697665722e706172746e65722e696e182ba1018250c8fa3674c4ed0eab3192771f1392030801 a80702116f64656c697665722e706172746e65721282582582826764656c6976657267706172746e65728183816764656c697665720182078206626f6b001364703a696e148183782664656c697665722e726571756573742e6f75743e64656c697665722e706172746e65722e696e82582582826764656c6976657267726571756573748183816764656c697665720182078206626f6b0001178283636f757400a60150827242f9de6b67f5bfcf5d6f6462d6f702508123dbaa681417af92bf1d659477f59e0350f09d9a552439b865d3e4c81c1d115313040105820257820f81826663686172676582088247470de4df8200001206818363617070686576656e745f69648206626f6b83646578697400a6015018b1f25dbecdd81fc5ac7139611721e502508123dbaa681417af92bf1d659477f59e0350f09d9a552439b865d3e4c81c1d1153130401058202581c82138269436f6d706c65746564820f818266737461747573820218c906818363617070686576656e745f69648206626f6b181981835018b1f25dbecdd81fc5ac7139611721e5782664656c697665722e706172746e65722e657869743e64656c697665722e6465636964652e696e82582482826764656c69766572666465636964658183816764656c697665720182078206626f6b00182ba2018250c8fa3674c4ed0eab3192771f13920308010282850650c8fa3674c4ed0eab3192771f1392030801501ec22e92983fdfaa9c62b22b6d57acba8250827242f9de6b67f5bfcf5d6f6462d6f75018b1f25dbecdd81fc5ac7139611721e5840750c8fa3674c4ed0eab3192771f139203080101 a80702116e64656c697665722e6465636964651282582482826764656c69766572666465636964658183816764656c697665720182078206626f6b0013676c3a737461727414801780181a5018b1f25dbecdd81fc5ac7139611721e5182282581d82816764656c697665728183816764656c697665720182078206626f6b00 a60702116e64656c697665722e6465636964651282582482826764656c69766572666465636964658183816764656c697665720182078206626f6b001364703a696e148183782664656c697665722e706172746e65722e657869743e64656c697665722e6465636964652e696e82582582826764656c6976657267706172746e65728183816764656c697665720182078206626f6b000117818364646f6e6500a60150d041f8468dc1be645ee0473d4b2d292d025018b1f25dbecdd81fc5ac7139611721e50350f09d9a552439b865d3e4c81c1d1153130401058202581e820f8282686576656e745f69648206626f6b8266737461747573820218c906818363617070686576656e745f69648206626f6b seal 15ab14a07ba6e7bd0b44195b6da8f7c9aae3b23d44b36e9f508e3936aae7db48 ```
## Carry forward Read [Connectors and outcomes](/guide/03-connectors-and-outcomes.md) for the admission boundary and [Running for real](/guide/05-running-for-real.md) for deployment settings, secrets and diagnostic evidence. This is the central exercise: one integration, several possible worlds, and a recorded explanation when a revision changes behavior. Keep the timeout, duplicate and 500 scenarios alongside the nominal one. Each describes a case the next change must still handle; passing them is evidence under their stated world assumptions, not proof that every real partner will behave that way. Previous: [Two tenants](/examples/03-two-tenants.md). Next: [Sensor alarm](/examples/05-sensor-alarm.md). The same approach can test an event that never arrives, without making the test wait in real time. ## Limits Malformed JSON, failed authentication and an excessive wire body are refused before a root or ACK exists. A decoded Lab injection cannot exercise that decoder. The separate physical loopback proof is: ```sh cargo test -p rastok --lib --features hosted-http12 auth_codec_and_body_refusals_never_invent_an_inbound_call ``` The filtered test result was: ```text test connector::drivers::network::http_server::tests::auth_codec_and_body_refusals_never_invent_an_inbound_call ... ok ``` An instance key isolates state; `seen` does the deduplication. This is accept-once within an **idle** retention window: duplicates extend that window, and a permanently failed job is still considered seen until expiry. It is not exactly-once delivery, a durable outbox, or automatic resubmission after a fault. A restart loses that state. The partner must honor the stable idempotency key, upsert by `event_id`; the request and key remain identical between attempts. Both retry paths rely on that external property. The example does not test a real partner's idempotence. The supplied privacy profile describes a local synthetic demonstration, not legal authority for production processing. Real purposes, recipients, transfers and retention require deployment-specific review. No persistent personal-data journal or `run --record` is admitted by this example. A message broker and SQL are not shown. Modify the scenario on disk to try another world; there is no debugger branch or payload editor. --- --- title: "The Lab: scenarios, mocks and time" description: Describe inputs, boundary outcomes and elapsed time as executable scenarios while keeping the application graph unchanged. url: https://docs.rastok.com/guide/04-the-lab source_revision: v0.2.0-alpha --- # The Lab: scenarios, mocks and time After this chapter you can read a Lab, override a mock, assert absence, advance virtual time, and distinguish simulation evidence from physical tests. ## Keep the program, supply its world The real world (App) uses physical Drivers; the virtual world (Lab) supplies scripted outcomes and time to the same graph. `lab smoke` contains shared mocks and scenarios directly. Its name need not match the App name. The Lab is not deployed and does not enter the program's semantic hash. Here is the entire Lab from `examples/echo.rkg`, lines 24–52: ```rkg lab smoke { mock shell { on in { out = . exit = Exited { exit_code = 0, signal = null } } } scenario roundtrip { app.in = "hello" expect app.out == "hello" expect shell.err == nothing } scenario filtered { app.in = "" expect shell.in == nothing expect app.out == nothing } scenario silence_expires { mock shell { on in { out = nothing } } app.in = "hello" advance duration("5s") expect shell.exit == TimeoutExpired {} } } ``` The mock supplies the Process response, not the Operator's decision. The real `relay` handler still filters the input. In `roundtrip`, the script returns the request data and one successful terminal. That response passes through the normal Contract and journal machinery, which creates its records. ## Group another mock world when needed An optional `simulation alternate { ... }` inside the Lab groups scenarios that share another set of mocks. It defaults to the unit's App; `: App` spells that target explicitly. A Lab mock applies to every group unless the group replaces it, and a scenario can replace either inherited mock. The replacement is the whole mock, never a merge of its branches. ## Silence must be explicit The `silence_expires` scenario replaces the whole shared mock for `shell`. Its `out = nothing` is deliberate silence, not an omitted response that the simulator guesses. The Call remains open until the explicit time advance reaches its five-second deadline. The runtime then produces the typed `TimeoutExpired` terminal. No child process was started. For an outbound Call, an uncovered request fails the scenario rather than silently timing out. A missing mock and an authored silent mock are different tests. Within a mock, the first matching clause in source order supplies the response. ## Read expectations in their action window An input injection or an `advance` starts an observation window. Subsequent expectations read that window without consuming it. They do not scan all earlier actions in the scenario. Ready work settles before those assertions are evaluated, so an expectation does not race a half-finished transition. `expect app.out == "hello"` checks exactly one matching value. `expect 3 app.out` checks three deliveries; omitting the number means one. `expect shell.in == nothing` asserts absence. The empty-input scenario therefore proves more than an empty App output: it proves that the Process was never called. Assertions observe ports, not an Operator's private state directly. An emission can be observed at its source even when the graph routes it to `nothing`. That is why the timeout can be asserted on `shell.exit` although Echo discards that output. `app.out`, in contrast, observes an actual crossing of the App boundary, not every child output. ## Advance to a deadline, not through a sleep The sensor example has a five-minute join window between a probe and a heartbeat. Its `virtual_day` scenario in `examples/sensor-alarm.rkg`, lines 73–78, supplies no heartbeat: ```rkg scenario virtual_day { app.probe = { sensor = "pump-a" } advance duration("24h") expect app.silent where data is JoinExpired expect app.alarm == nothing } ``` The advance visits the five-minute expiry before reaching its twenty-four-hour target. ```mermaid flowchart LR probe["t = 0: app.probe"] --> advance["advance: target 24 hours"] advance --> expiry["t = 5 minutes: JoinExpired"] expiry --> expect["t = 24 hours: expect app.silent"] ``` Ready computations take no virtual time. The simulator processes due obligations in order, settling Call and resident Process Session mock replies and their consequences before the next deadline, without another `advance` or real sleep. ## Inspect source Follow [the debugger tour](/debugger.md): source left, inspector and Graph right. **Next transition** (`F10` or `n`) follows recorded transitions. Hover or focus runtime identifiers for redacted, read-only summaries and inspector links; Escape closes them. **Fit graph** shows everything; **Readable size** restores interface-sized text. Choose scenarios; click progress to select their source. ## Know the evidence boundary Run `rastok simulate examples/echo.rkg` to check its three scenarios. Add `--compare examples/traces/echo` to compare their causal traces as well. Expectations express selected requirements; the golden comparison can reveal other changed facts. `--save` writes new references and is a separate, reviewed action. A scripted outcome proves how the checked graph responds to that outcome. It does not prove a real partner obeys the Contract. In particular, a decoded HttpServer Lab injection cannot test malformed wire JSON or authentication before admission. Automatic incident-to-scenario conversion and authored crash/restart actions are not executable Lab features today; see [the current limits](/index.md#what-is-available-today). See [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md), [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) section 8, and `WHITEPAPER.md` sections 5 and 6 for the normative rules and context. ## Summary - A mock substitutes the external response, not the graph's computation. - Silence and absence are authored, observable test cases. - Expectations read the latest action window. - Virtual time resolves real graph obligations without waiting in real time. ## Next Read [Running for real](/guide/05-running-for-real.md). Experiment with [Echo](/examples/01-echo.md) and [Sensor alarm](/examples/05-sensor-alarm.md) to compare ordinary replies, silence and time-dependent outcomes. --- --- title: Migrating from 0.1 to 0.2 description: Port a 0.1 graph, handle missing values and check its scenarios against your existing reference traces. url: https://docs.rastok.com/migration source_revision: v0.2.0-alpha --- # Migrating from 0.1 to 0.2 Start with the `.rkg` source and keep your 0.1 binary, recordings and reference traces. Change the spellings first. Then run `rastok check`: some diagnostics ask you to make a decision, such as when a keyed instance should stop or what to do when a list is empty. The [authoring rules](/reference/authoring-rules.md) pair these refusals with working 0.2 code. ## Rename the spellings, not the data | In 0.1 | In 0.2 | What to keep in mind | |---|---|---| | Type `text` | `string` | Change declarations, type tests and casts. Do not edit the text inside string literals. You can declare `type text = string` in your own unit; it covers type positions only. | | Verbatim block `text! { received }` | `string! { received }` | Change only the reader name. The spaces inside the braces are part of the value. | | `codec = text` | `codec = string` | Applies to HttpClient, HttpServer, WebSocketClient and WebSocketServer. The wire encoding stays the same. The codec word is part of the plan's identity. | | Process overflow reason `budget` or `capacity` | `Budget` or `Capacity` | These are enum symbols. Update matches, mocks and JSON consumers: JSON carries the exact spelling. | | `@sensitive(level = confidential)` | `@sensitive(level = Confidential)` | Use `Internal`, `Confidential` or `Restricted`. The protection level keeps its identity. Configuration words such as `codec = json` and `kind = age` stay lowercase. | The old type without an alias, and the old reader with or without one, produce `E-RESOLVE-UNKNOWN`. The old network codec produces `E-CONTRACT-ATTR`. ## Choose when an instance closes Give every `var` an initial value. Write `var last: string = ""` for an empty string, or `var last: string? = null` if it starts absent. If you omit the initializer, `check` points to the declaration and suggests a fix. | In 0.1, inside `lifetime` | In 0.2 | When the instance closes | |---|---|---| | `kind = fixed; after = D` | `kind = age; max = D` | After the elapsed time measured from creation. | | `kind = tumbling; every = D` | `kind = slot; max = D` | At the end of its processing-time slot. | | `kind = single_pass` | `kind = once` | After one admission. | | `kind = idle; after = D` | `kind = idle; max = D` | After no admissions for the specified duration. | Here `D` stands for a positive duration such as `duration("5m")`. The old kinds and fields produce `E-INSTANCE`. Do not rename `every` on a Timer or change a Retry delay. A Graph, Operator or Connector that declares an instance key must also declare a lifetime (`E-LIFETIME-REQUIRED`). Add `lifetime = { kind = persistent }` to keep the old behavior and hash. That also keeps every key alive until explicitly stopped. If a keyed Operator can finish its first reaction without retaining state or stopping, `check` warns with `W-EMPTY-INSTANCE`: that empty instance has no deadline. For a session that should expire after two hours of silence, use `lifetime = { kind = idle; max = duration("2h") }` instead. Without a key, omitting the lifetime still gives a persistent singleton. See [Instances, state and time](/guide/06-instances-state-and-time.md) for closure budgets: every finite owner containing an outbound Connector has to declare both budgets, including the App. This is not specific to Process. ## Handle a value that may be missing | In 0.1 | In 0.2 | |---|---| | `xs[i]` with no proof the index exists | Use `xs[?i]`; an out-of-range index gives null. | | `m[k]` or `m.name` with no proof the key exists | Use `m[?k]` or `m.?name`. Mark each step that can be absent. | | `x as T` when the conversion can fail | Test `x is T` before using it, or use `x as? T` and handle null. | | `timestamp(s)`, `duration(s)` or `decimal(s)` on runtime text | The same call yields an optional value. For example, sending `timestamp(s)` straight to a `timestamp` port gives `E-PORT-TYPE`. Test the value, match it or supply a meaningful default with `.orValue(default)`. | | A malformed constant such as `timestamp("not a date")` | Correct the literal: `check` rejects it with `E-EXPR`, including inside a reaction. | | `meta.app.id` when some incoming routes write `id` and others do not | Write it on every route, or use `meta.app.?id` and handle absence. The required read reports `E-META-ZONE` and names the route's origin. If the graph never writes `id`, even the optional read is refused. | Plain lookups and casts still work when the type, a constant or a type test in scope proves they succeed. Otherwise they report `E-EXPR`. A test such as `size(xs) > 0` is not an index proof. If the result type is `variant`, it already includes null: for a string fallback on a variant map, write `(m[?k] as? string).orValue("unknown")`. Here an empty list really does mean “unassigned”. Save this as `labels.rkg` and run `rastok simulate labels.rkg` to check both paths: ```rkg graph labels : App { input in: array output out: string operator first { input in: array output out: string on in { out = data[?0].orValue("unassigned") } } in -> first -> out } lab labels { scenario has_label { app.in = ["blue"] expect app.out == "blue" } scenario no_label { app.in = [] expect app.out == "unassigned" } } ``` The Lab prints: ```text PASS labels.has_label PASS labels.no_label 2 scenario(s), 0 failed ``` If absence should reject a request instead, keep the optional value and route that case explicitly. The ternary, scenario, mock and expectation syntax has not changed. See [Expressions and dispatch](/reference/expressions.md). ## Check numeric and boundary types | In 0.1 | In 0.2 | |---|---| | `uint` for an unsigned 64-bit field | Use `ulong` to preserve its range. Keep `uint` only if 32 bits are intended. The suffix `u` chooses the first width that fits: `7u` is a `uint`, `4294967296u` a `ulong`. | | `number` for an exact value | Use `decimal` for an exact value with free scale, or keep `decimal(p,s)` for a declared scale. For a binary floating result from a `variant`, use `as? double` and handle null. | | `bytes` or `bytes(n)` as a type | Use `array` or `array`. The compact encoding and the `bytes` codec stay the same. JSON does not implicitly convert bytes to base64. | | `media_type` or `media_type(s)` | Use `string` and the string value itself. The reserved `meta.ext.content_type` is a `string(255)`: the entire value, including parameters, must still be a valid MIME Content-Type. Other strings have no MIME requirement. | | HttpClient `DecodeFailed {}` in a mock or exact expectation | `DecodeFailed { message = "…" }` | A numeric literal can take the expected type if it fits. A calculated value widens implicitly only if its whole type fits. For example, an `int` and a `uint` can meet at `long`. A `long` does not always fit a `double`: use `as? double` when the conversion depends on the value. Schemaless JSON reads a number as `long`, `ulong` or `double`, in that order, and rejects it if none preserves its value. Declare an exact decimal at the boundary when that is what the protocol requires. See [Types and schemas](/reference/types.md). **HttpClient.** For `http://`, the default works with an HTTP/1.1 server. Select only `"http/2"` when the server expects cleartext HTTP/2. For a response with status 204 or 205, handle `Completed` on `exit`. Do not wait for a body on `out` or supply one in the corresponding mock. For a typed JSON response, declare a `timestamp` field to read an RFC 3339 UTC string ending in `Z`. If a declared field cannot be read, the Call ends with `DecodeFailed` and delivers nothing on `out`. The message names the declared field and the expected type. If the body is not JSON, it names `out` instead. For a request that cannot be encoded, it names `in` and the expected representation; no request is sent. Neither message includes a rejected value or a key supplied by the peer. Keep a case test such as `data is DecodeFailed`. In that branch you can read `data.message`. Supply a message when constructing the case: in a mock, `exit = DecodeFailed {}` now gives this diagnostic: ```text error[E-PORT-TYPE]: `DecodeFailed` requires field `message: string` ``` The [HttpClient contract](/reference/connectors/http-client.md) stays at `@1`. This change does not affect WebSocket cases or make timestamps writable as JSON. ## Recompile and compare A schemaless JSON codec delivers an object as a map, including when a mock writes a record. If all sources of an input deliver schemaless JSON, replace `data is Receipt` with `val receipt = data as? Receipt` and handle null. The mock still receives the graph's typed request. The format 2 plan reader rejects a format 1 `.rkp`: recompile the ported `.rkg` source. Diagnostic recordings (`.rkr`) keep format 1, but replay also checks the plan embedded in the recording. Keep the 0.1 binary to replay recordings with a format 1 plan. Run `rastok check` and then `rastok simulate` before using real Drivers. Compare against the existing `.rkc` references first. For example, from the repository root: ```sh rastok check examples/echo.rkg rastok simulate examples/echo.rkg --compare examples/traces/echo ``` A different plan hash is not by itself a different delivery. Review the first differing record, including whether only a recorded Retry plan hash changed. If you intend to change the reference, use `--save` in a separate directory and review the differences before replacing the old files. --- --- title: HttpServer description: Ports, terminal outcomes, settings and qualification evidence for the HttpServer connector. url: https://docs.rastok.com/reference/connectors/http-server source_revision: v0.2.0-alpha --- # HttpServer `std/http-server@1`. An inbound HTTP Call. `ack` sends 202 after admission; `respond` waits for the graph response. A malformed body or failed authentication can refuse before admission, without inventing a request envelope or an exit. ## Declaration This declaration comes from `crates/rastok/src/lab.rs`. Place the Connector in a Graph and wire its ports; the excerpt alone is not an App. ```rkg connector network : HttpServer { listen = "127.0.0.1:8080" codec = json } ``` The [contract index](/reference/contracts.md) explains shared settings, build features and the distinction between a Contract, a Lab model and an installed Driver. Selector: `mode` defaults to `ack`. See [inbound admission and backpressure](/reference/execution.md#instances-own-state-not-threads): pending requests are retained within bounds, and the outbound Call queue rule does not apply to this Contract. | Mode | Driver direction | Exchange | Lab model | Installed in this binary | |---|---|---|---|---| | `ack` | inbound | call | `lab-http-server` | Not compiled | | `respond` | inbound | call | `lab-http-server` | Not compiled | ## Ports and completion | Mode | Port | Direction | Type rule | |---|---|---|---| | ack, respond | `in` | input | `codec = bytes` → `array`; `codec = json` → `variant`; `codec = string` → `string` | | ack, respond | `out` | output | Same as `in` | | ack, respond | `exit` | output | HttpServerExit, below | | Mode | Output cardinality | |---|---| | ack | One admitted request `out`; exactly one request `exit`; no graph response | | respond | One admitted request `out`; exactly one request `exit`; at most one response `in` | ## Exit union | Case | Payload | Call visibility | |---|---|---| | `Completed` | `{ status: int }` | Not an outbound Call | | `OutcomeUnknown` | Empty | Not an outbound Call | | `Overloaded` | Empty | Not an outbound Call | | `PeerDisconnected` | Empty | Not an outbound Call | | `RequestExpired` | Empty | Not an outbound Call | ## Settings In `mode = respond` with `codec = json`, `rastok check` refuses a graph response whose resolved type contains a [value without a JSON form](/reference/types.md#json-request-values), using `E-TYPE-INVALID`. A `variant` response is checked at execution instead; if its value cannot be encoded, the Driver sends HTTP 500 and reports `OutcomeUnknown`, without sending that value. | Mode | Setting | Domain | Presence / default | Latest phase | |---|---|---|---|---| | ack, respond | `auth_bearer` | `string` | optional | instance | | ack, respond | `behavior` | `deterministic` | `deterministic` | plan | | ack, respond | `codec` | `bytes \| json \| string` | required | plan | | ack, respond | `headers` | `HTTP headers` | optional | instance | | ack, respond | `custom_headers` | `map>` | optional | instance | | ack, respond | `listen` | `string` | required | instance | | ack, respond | `max_body` | `ByteSize` | `"8MiB"` | plan | | ack, respond | `path` | `string` | `"/"` | plan | | ack, respond | `tls_certificate` | `array` | optional | instance | | ack, respond | `tls_private_key` | `array` | optional | instance | | ack, respond | `versions` | `array` | `["http/3", "http/2", "http/1.1"]` | plan | | ack, respond | `zero_rtt` | `disabled` | `disabled` | plan | | respond | `correlate` | `expression path` | optional | invocation | | respond | `timeout` | `duration` | required | instance | The Lab scripts decoded `ack` requests through `listener.out = value`, then a successful 202. It does not exercise wire decoding or authentication. A `respond` Node can bind silently beside another simulated flow; authored source injection and graph-response scripting for that mode are deferred. ## Qualification inventory `ack`: No dedicated full-Contract fixture is declared. Related tests: `crates/rastok/src/connector/drivers/network/http_server.rs`, `crates/rastok/tests/lab_http_source.rs`. `respond`: No dedicated full-Contract fixture is declared. Related tests: `crates/rastok/src/connector/drivers/network/http_server.rs`, `crates/rastok/tests/lab_http_source.rs`. --- --- title: Standard contracts description: Contract identities, modes, ports, terminal cases, settings and Lab support from the executable Connector catalogue. url: https://docs.rastok.com/reference/contracts source_revision: v0.2.0-alpha --- # Standard contracts This inventory follows `rastok connectors --json` in its emitted order. Contract availability, Lab models and installed physical Drivers are separate facts. A binary built with default features (no networking) lists File and Process Drivers; networking requires the hosted networking features. Run the command on the binary you deploy to inspect that assembly. The [standard exit types](/reference/stdlib.md#types) are available by name without imports. The physical Driver selection does not change those type definitions. A finite owner of an outbound Connector declares the drain and settlement budgets in `closing`. This applies to the App as well as nested owners. A setting's latest phase is its evaluation ceiling: plan, boot, instance or invocation. A setting may depend on values available by that phase, but not on values that become available later. The compiler selects the earliest phase where its expression closes. Omitted defaults become effective settings. Optional means absent, not null. Byte sizes use `B`, `KiB`, `MiB` or `GiB`. HTTP-derived Contracts share `headers` (a sparse typed record containing `content_type: string(255)`) and `custom_headers` (`map>`). Driver-owned headers cannot be overridden. Certificate and private-key settings must be supplied together. Declared version preferences are HTTP/3, HTTP/2, HTTP/1.1; the Driver uses only compiled backends. `hosted-http12`, `hosted-http3` and `hosted-websocket` select those capabilities. `hosted-network` enables the hosted networking group. `idempotent` is a repetition guarantee. `behavior` describes whether equal requests in equal external state yield equal answers. They are distinct; [Retry](/guide/07-loops-and-retries.md) also checks terminal visibility. Sessions have no per-message Call exit or Retry attribute. ## Connectors - [File](/reference/connectors/file.md): Read or atomically replace a file. - [Process](/reference/connectors/process.md): Start a job or keep a resident process. - [HttpClient](/reference/connectors/http-client.md): Send a request and receive its response and terminal outcome. - [HttpServer](/reference/connectors/http-server.md): Admit a request and acknowledge it or await the graph's response. - [WebSocketClient](/reference/connectors/websocket-client.md): Open a peer Session and exchange messages. - [WebSocketServer](/reference/connectors/websocket-server.md): Accept peer Sessions and route their messages. ## Specified, not shipped | Item | Specification | |---|---| | File `watch`: listed as checker deferred; attributes only, no Driver, Lab model, fixture or example | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §3.7 | | Timer: elapsed-time source | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §3.4 | | Calendar: civil schedule source | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §3.5 | | Memory: bounded append/snapshot store | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §3.6 | | HttpServer `respond` source scripting in the Lab | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §2 | | Streaming HttpServer responses and seeded behavior | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §8 | Fixture names describe the evidence corpus, not checks performed by the catalogue command. Source authority: [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md), resolved standard definitions and the current binary's catalogue. For authoring, see [Connectors and outcomes](/guide/03-connectors-and-outcomes.md). --- --- title: "Sensor alarm: make time an input" description: Isolate hysteresis state by sensor, detect a missed heartbeat with a bounded join, and advance through a virtual day without waiting a day. url: https://docs.rastok.com/examples/05-sensor-alarm source_revision: v0.2.0-alpha --- # Sensor alarm: make time an input This program tracks each sensor's readings, emits alarm changes and reports a missing heartbeat. The partner example tested a response and a timeout. Now ask a harder question: how do you test silence? Keep state per sensor, distinguish a threshold crossing from noise, and make the waiting period an explicit input to your scenario. The [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for the program and Lab, `.rkc` for a reviewed scenario reference and `.rkr` for a real execution recording. ## Run From the repository root, with `rastok` installed: ```sh rastok simulate examples/sensor-alarm.rkg --compare examples/traces/sensor-alarm ``` ```text PASS sensors.hysteresis PASS sensors.silent_sensor PASS sensors.virtual_day 3 scenario(s), 0 failed ``` The four lines above are stdout. The same command writes two warnings to stderr: ```text warning[W-EMPTY-INSTANCE]: `hysteresis` can open an instance that retains nothing on `in` --> examples/sensor-alarm.rkg:31:7 | 31 | _ => nothing | ^^^^^^^^^^^^ = owner: hysteresis = trigger: in = help: give the instance a delay, or add `stop` if that branch ends its work warning[W-EMPTY-INSTANCE]: `watchdog` can keep an instance that retains nothing after `on (probe, heartbeat)` --> examples/sensor-alarm.rkg:41:49 | 41 | on (probe, heartbeat) within duration("5m") { | ^ = owner: watchdog = trigger: (probe, heartbeat) = help: give the instance a delay, or add `stop` if that branch ends its work ``` A first reading can leave `hysteresis` unchanged, and `watchdog` keeps no state after consuming a pair. Both Operators intentionally keep the sensor instance for later messages; neither warning changes the trace. ## Read the program First follow the readings into the keyed stateful Operator: its two thresholds prevent an alarm from oscillating around one limit. Then find the `watchdog` join. A probe and heartbeat rendezvous within a bounded interval; a missing partner produces `JoinExpired`, whose route is as explicit as a normal output. Read `advance` in the Lab last: time comes from the scenario, not from sleeps hidden in the application. `var tripped: bool = false` is the memory behind that behavior: a boolean cell initialized to `false` for each sensor's Operator instance. At 121, pump-a sets it to `true` and emits `tripped`; at 100, it keeps that state and emits nothing; at 79, it resets the cell and emits `normal`. Pump-b's cell is independent and starts at `false`, so its reading of 100 produces no alarm. Each state change commits together with its emission, not as a separate shared assignment. The preceding webhook example uses `var seen` for the same kind of private memory. See [Values and mutable state](/guide/06-instances-state-and-time.md#values-and-mutable-state) for the difference between `var`, `val` and an instance key. There is no Connector in this program. The [Lab reference](/reference/lab.md) explains expectations and observation windows; `advance` supplies virtual time. Source: `examples/sensor-alarm.rkg` ```rkg // Hysteresis per sensor and a bounded probe/heartbeat rendezvous. // The Lab supplies clock advances, not a real periodic sensor Driver. type Reading = struct { sensor: string, value: int } type Sensor = struct { sensor: string } type Alarm = struct { sensor: string, state: string } type MissedHeartbeat = union { JoinExpired {} } graph sensor_alarm : App { input reading: Reading input probe: Sensor input heartbeat: Sensor output alarm: Alarm output alive: string output silent: MissedHeartbeat operator hysteresis { input in: Reading output out: Alarm instance = { key = data.sensor } lifetime = { kind = persistent } var tripped: bool = false on in match { !tripped && data.value > 120 => { tripped = true out = { sensor = data.sensor; state = "tripped" } } tripped && data.value < 80 => { tripped = false out = { sensor = data.sensor; state = "normal" } } _ => nothing } } operator watchdog { input probe: Sensor input heartbeat: Sensor output out: string output expired: MissedHeartbeat instance = { key = data.sensor } lifetime = { kind = persistent } on (probe, heartbeat) within duration("5m") { out = probe.data.sensor } } reading -> hysteresis -> alarm probe -> watchdog.probe heartbeat -> watchdog.heartbeat watchdog.out -> alive watchdog.expired -> silent } lab sensors { scenario hysteresis { app.reading = { sensor = "pump-a"; value = 121 } expect app.alarm where data.sensor == "pump-a" && data.state == "tripped" app.reading = { sensor = "pump-a"; value = 100 } expect app.alarm == nothing app.reading = { sensor = "pump-b"; value = 100 } expect app.alarm == nothing app.reading = { sensor = "pump-a"; value = 79 } expect app.alarm where data.state == "normal" } scenario silent_sensor { app.probe = { sensor = "pump-a" } app.probe = { sensor = "pump-b" } app.heartbeat = { sensor = "pump-b" } expect app.alive == "pump-b" advance duration("5m") expect app.silent where data is JoinExpired expect app.alive == nothing } scenario virtual_day { app.probe = { sensor = "pump-a" } advance duration("24h") expect app.silent where data is JoinExpired expect app.alarm == nothing } } ``` ## Expected result The golden's `sensors.virtual_day` follows one unanswered probe, not the separate hysteresis scenario; the advance visits its five-minute deadline. ```mermaid sequenceDiagram participant lab as Lab: sensors.virtual_day participant app as sensor_alarm participant watchdog as watchdog lab->>app: probe = pump-a app->>watchdog: probe = pump-a Note over watchdog: Wait for heartbeat within 5m lab->>lab: advance 24h Note over watchdog: At 5m: no matching heartbeat watchdog-->>app: expired to silent = JoinExpired Note over lab,app: Advance completes at 24h, no alarm emitted ``` Pump-a trips above 120, stays tripped at 100, and clears below 80. Pump-b has independent state. A keyed join pairs a probe with a heartbeat within five minutes; only the unanswered probe expires in the silent-sensor scenario. The final scenario advances twenty-four virtual hours in one authored action. With Ruby and the built `target/debug/rastok` available, this command measures process wall time on your machine; it does not change the scenario's logical time: ```sh ruby -e '3.times { t = Process.clock_gettime(Process::CLOCK_MONOTONIC); ok = system(*ARGV); puts format("elapsed_cli_seconds=%.6f", Process.clock_gettime(Process::CLOCK_MONOTONIC) - t); exit 1 unless ok }' target/debug/rastok simulate examples/sensor-alarm.rkg ``` ## Break it Raise the trip threshold from 120 to 130. The sample at 121 no longer trips, and the original assertion and golden fail. Alternatively, remove the route from `watchdog.expired`: the checker refuses `E-UNWIRED-OUTPUT` before execution. ```sh rastok simulate examples/sensor-alarm.rkg --compare examples/traces/sensor-alarm ``` ```text FAIL sensors.hysteresis expect app.alarm where data.sensor == "pump-a" && data.state == "tripped" (sensor-alarm.rkg:56) nothing observed where data.sensor == "pump-a" && data.state == "tripped" is false for 0 of 0 deliveries; count 0, expected 1 expect app.alarm where data.state == "normal" (sensor-alarm.rkg:62) nothing observed where data.state == "normal" is false for 0 of 0 deliveries; count 0, expected 1 golden divergence: record 3: emissions(23).len; expected 1; got 0; cause: TRANSACTION "hysteresis" · trigger "p:in" · cause_id absent PASS sensors.silent_sensor PASS sensors.virtual_day 3 scenario(s), 1 failed ``` Restore the checked-in source (this discards your edits to this example): ```sh git checkout -- examples/sensor-alarm.rkg ``` ## Read the golden difference The threshold edit changes a recorded Operator transaction, including its state delta and emitted alarm. The diff gives the first changed record, expected/actual values and causal trigger. The missing expiry route is a static error, not a runtime golden difference.
Inspect the raw sealed trace (.rkc) The versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence. Source: `examples/traces/sensor-alarm/sensors.virtual_day.rkc` ```rastok-trace a7070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820254820f81826673656e736f7282066670756d702d6109636c61620a000b000c6570726f62650d8182752e70726f62653e7761746368646f672e70726f62658258238281687761746368646f67818381687761746368646f6701820782066670756d702d6100 a7070211601282438280800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8 a8070211687761746368646f67128258238281687761746368646f67818381687761746368646f6701820782066670756d702d610013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c81822824382808000 a7070211687761746368646f67128258238281687761746368646f67818381687761746368646f6701820782066670756d702d610013676c3a6576696374148183752e70726f62653e7761746368646f672e70726f626582438280800001178183676578706972656400a50150354e01026e2d3e4214fc54f4c1b6c8900250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c80401058202528213826b4a6f696e45787069726564820f80181a50f3df1105112054d397a04ed0666ca4c8 seal 9de2f8f4a2c1ad627873679b88408b9d90f101d99ba146d4e2362cd30ae4af75 ```
## Carry forward [The Lab](/guide/04-the-lab.md) explains this example's virtual clock and the observation window used by its expectations. Time, like an external response, is something you can supply deliberately. You can retain a missed heartbeat as a small regression scenario instead of waiting for the fault to recur on equipment. Types, state ownership and the same causal comparison still apply; the device domain needs no special Lab. The core evaluating this graph has no clock, network access or randomness; time and external outcomes enter as explicit inputs. CI compiles `rastok-core` for targets without an operating system: `thumbv8m.main-none-eabihf`, `thumbv7m-none-eabi` and `riscv32imac-unknown-none-elf`. It also runs the RP2350 spike under QEMU's Cortex-M33 emulation. Running this sensor example on a physical board is not part of the alpha. Previous: [Webhook to partner](/examples/04-webhook-to-partner.md). Next: [Agent gateway](/examples/06-agent-gateway.md): keep a separate resident process for each conversation and interleave several turns. Before moving on, try writing a second silent-sensor scenario and explaining its first expiry from the journal. ## Limits This is a requested probe/heartbeat rendezvous, not automatic periodic polling. No sensor protocol, process or paid model runs. An unmatched value on either join input can produce `JoinExpired`; the scenarios explicitly control which side is silent. Expiry DATA has no sensor field: its keyed instance and causal history supply that context. The benchmark tasks informed the example, but no claim is made that a published model wave authored it. --- --- title: Running for real description: Move from scripted outcomes to physical Drivers while keeping deployment settings, secrets, evidence and alpha limits explicit. url: https://docs.rastok.com/guide/05-running-for-real source_revision: v0.2.0-alpha --- # Running for real After this chapter you can choose between simulation, a real run and diagnostic replay. You can identify the deployment information that a graph needs, keep credentials out of source, and distinguish a reviewed golden from a recording of one real execution. ## Change the world, not the graph `rastok run` compiles the App and uses physical Drivers. Its inputs and external responses are no longer supplied by Lab scenarios. Before trying a network integration, inspect `rastok connectors` in the binary you will use: checker support and an installed physical implementation are separate requirements. Getting Started installs the documented hosted features. Echo is a small local first run. From the repository root, with a new recording filename: ```sh printf 'hello\n' | rastok run examples/echo.rkg --record echo.rkr rastok replay echo.rkr ``` The first command starts the real `cat` process and prints its echoed line. Replay prints the recorded App output and the same causal seal without starting `cat` again. The original source file is not needed by the recording reader. An existing recording path is refused rather than overwritten. ## Supply deployment facts explicitly The webhook example needs more than a command name. Its partner Connector, from `examples/webhook-to-partner.rkg`, lines 80–96, separates a URL binding and a secret reference from the application logic: ```rkg connector partner : HttpClient + Retry { url = env("PARTNER_URL") auth_bearer = secret("showcase/partner/token") method = "POST" codec = json output out: Receipt timeout = duration("1s") max_body = "16 KiB" idempotency_key = meta.app.event_id // Required partner contract: honour this key for the identical request. // This declaration does not prove that a real service honours that contract. idempotent = true behavior = deterministic Retry.attempts = 2 Retry.on = [ServerError, TimeoutExpired, DnsFailed, ConnectFailed] Retry.delay = { kind = fixed; after = duration("1s") } } ``` In the alpha, `env()` is admitted at `HttpClient.url`, and `secret()` at `HttpClient.auth_bearer`. They are not general environment-reading functions available in every expression. The deployment JSON names non-secret values and the secret's provider coordinate and version. Actual secret material is supplied out of band; the provider version must match the attestation. Do not paste a credential into the graph, profile JSON or a shell command. `examples/webhook-to-partner.deployment.json` is a synthetic Lab profile, not production authorization. The example's Run section supplies an explicitly fictional token and its matching version. The same profile also attests the personal-data policy required by the annotated email field. Missing or contradictory coverage refuses before effects. Redaction is not permission to persist that data indefinitely. ## Repeat only under a real guarantee `Retry.attempts = 2` includes the first attempt. The manager retains the same request, waits the declared delay after a selected terminal, then tries again within that bound. Intermediate attempt facts remain in the journal; only the final attempt is delivered downstream. The partner must actually honor the idempotency key for the identical operation. Declaring `idempotent = true` cannot make an arbitrary remote action safe to repeat. A timeout alone does not prove that it did nothing. `Loop` instead advances application state, and keyed instances own isolated state and lifetime. Their detailed protocols belong to later chapters; [Two tenants](/examples/03-two-tenants.md) already demonstrates isolation. ## Choose the evidence you need A golden is a reviewed canonical trace of a Lab scenario. `simulate --compare` checks stored references without changing them and names the first divergence in each differing scenario. `--save` creates or replaces references, so review the semantic reason before saving. Neither option supplies mock responses; those remain in the Lab. A diagnostic recording contains the real run's plan and journal evidence. Replay reconstructs that evidence, not a fresh execution or a generated scenario. The journal is currently in memory. A recording is bounded local diagnostic storage, not a durable deployment journal, automatic restart mechanism or share-safe export. Do not apply the Echo recording command indiscriminately to the webhook graph. The current recorder refuses personal-data plans, nonempty deployment attestations and boot-dependent Connector settings before file creation or effects. Ordinary unclassified payloads can still be sensitive. Protect the file rather than assuming the debugger's masking rewrites its stored bytes. `simulate --ui` opens paused and executes the scenario forward under your control. Its history controls inspect recorded transitions. `replay --ui` only navigates recorded prefixes, with no Driver I/O. Neither edits the graph or forks a new world, and `run --ui` is not supported. The webhook's typed response also retains original annotated measurements before Retry decides whether to hold or publish an attempt. Missing usage is not zero. The alpha does not calculate a bill, aggregate costs or enforce a Budget Extension. These limits are listed with the other [current capabilities](/index.md#what-is-available-today). The normative reading is [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md), [`docs/spec/observability.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/observability.md), [`docs/spec/annotations.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/annotations.md) and [`docs/spec/ui.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/ui.md). The recording contract is `docs/architecture/diagnostic-recording.md`. ## Summary - Real execution needs compatible physical Drivers and explicit deployment facts. - A secret reference is not its material; an attestation is not a source literal. - Goldens compare scenarios; recordings reconstruct one captured run. - Retry safety and privacy still require real external guarantees. ## Next Continue with [Instances, state and time](/guide/06-instances-state-and-time.md) for state ownership, lifetimes and bounded closure. [Command line](/guide/09-command-line.md) lists every command and its options, or try [Webhook to partner](/examples/04-webhook-to-partner.md). Run its synthetic scenarios, inspect the bounded retry, then review what a real partner and deployment must supply. Return to [Getting Started](/getting-started.md#three-ways-to-learn) to choose another example. --- --- title: WebSocketClient description: Ports, terminal outcomes, settings and qualification evidence for the WebSocketClient connector. url: https://docs.rastok.com/reference/connectors/websocket-client source_revision: v0.2.0-alpha --- # WebSocketClient `std/websocket-client@1`. Opens a peer Session. Each complete message is one value; each graph write is journaled before I/O. One terminal ends the Session, not a message. ## Declaration This declaration comes from `crates/rastok/src/lab.rs`. Place the Connector in a Graph and wire its ports; the excerpt alone is not an App. ```rkg connector network : WebSocketClient { url = "wss://example.test/socket" handshake_timeout = duration("5s") codec = json behavior = deterministic } ``` The [contract index](/reference/contracts.md) explains shared settings, build features and the distinction between a Contract, a Lab model and an installed Driver. See [instance ownership and bounded admission](/reference/execution.md#instances-own-state-not-threads); this Contract uses Sessions, not the outbound Call queue rule. | Mode | Driver direction | Exchange | Lab model | Installed in this binary | |---|---|---|---|---| | No selector | inbound+outbound | session | `lab-websocket` | Not compiled | ## Ports and completion | Mode | Port | Direction | Type rule | |---|---|---|---| | all | `in` | input | `codec = bytes` → `array`; `codec = json` → `variant`; `codec = string` → `string` | | all | `out` | output | Same as `in` | | all | `exit` | output | WebSocketExit, below | | Mode | Output cardinality | |---|---| | all | Zero or more frames and writes; exactly one `exit` per Session | ## Exit union | Case | Payload | Call visibility | |---|---|---| | `Closed` | `{ code: int, reason: string }` | Not an outbound Call | | `ConnectFailed` | Empty | Not an outbound Call | | `DecodeFailed` | Empty | Not an outbound Call | | `DnsFailed` | Empty | Not an outbound Call | | `HandshakeRejected` | `{ status: int }` | Not an outbound Call | | `MessageTooLarge` | `{ limit: ulong }` | Not an outbound Call | | `OutcomeUnknown` | Empty | Not an outbound Call | | `ProtocolFailed` | Empty | Not an outbound Call | | `TimeoutExpired` | Empty | Not an outbound Call | | `TlsFailed` | Empty | Not an outbound Call | | `TransportLost` | Empty | Not an outbound Call | ## Settings With `codec = json`, `rastok check` refuses a producer whose resolved type contains a [value without a JSON form](/reference/types.md#json-request-values), using `E-TYPE-INVALID`. A `variant` producer is checked at execution instead: an unencodable message ends the Session with `DecodeFailed` before it is sent. | Mode | Setting | Domain | Presence / default | Latest phase | |---|---|---|---|---| | all | `auth_bearer` | `string` | optional | instance | | all | `behavior` | `deterministic \| probabilistic` | required | plan | | all | `codec` | `bytes \| json \| string` | required | plan | | all | `handshake_timeout` | `duration` | required | instance | | all | `headers` | `HTTP headers` | optional | instance | | all | `custom_headers` | `map>` | optional | instance | | all | `max_message` | `ByteSize` | `"8MiB"` | plan | | all | `subprotocols` | `array` | optional | instance | | all | `tls_ca` | `array` | optional | instance | | all | `tls_certificate` | `array` | optional | instance | | all | `tls_private_key` | `array` | optional | instance | | all | `url` | `string` | required | instance | | all | `versions` | `array` | `["http/3", "http/2", "http/1.1"]` | plan | | all | `zero_rtt` | `disabled` | `disabled` | plan | The Lab has an effectless Session binding, but authored WebSocket Session mocks are not executable. `rastok check` refuses a `mock` on this Connector with `E-CHECK-DEFERRED`; a declaration without a mock still checks. Driver tests cover Session opening, frames, writes and terminal outcomes separately. Input after a terminal may open a successor Session; old writes are not resent automatically. ## Qualification inventory No dedicated full-Contract fixture is declared. Related tests: `crates/rastok/src/connector/drivers/network/websocket.rs`. --- --- title: The Lab description: Executable Lab declarations, mock responses, scenario actions, observation windows and golden-trace commands. url: https://docs.rastok.com/reference/lab source_revision: v0.2.0-alpha --- # The Lab The real world (App) supplies external observations through Drivers. The virtual world (Lab) supplies scripted observations and logical time to the same graph. Operators and Contract checks execute in both. ## Declarations Save this complete program as `lab-reference.rkg`, then run `rastok check lab-reference.rkg` and `rastok simulate lab-reference.rkg`. The mock replaces the HTTP partner; simulation makes no network request. ```rkg graph lab_reference : App { input in: string output out: string output exit: HttpClientExit connector partner : HttpClient { url = "https://partner.example.test/messages" method = "POST" codec = string behavior = deterministic timeout = duration("5s") } in -> partner partner.out -> out partner.exit -> exit } lab replies { // Direct scenarios and simulations inherit this mock. mock partner { on in { out = . exit = Completed { status = 200 } } } scenario echoes_the_request { app.in = "hello" expect app.out == "hello" expect app.exit == Completed { status = 200 } } // An optional group can replace the inherited mock for all its scenarios. simulation silent_partner { mock partner { on in { out = nothing } } scenario times_out_without_a_reply { app.in = "hello" expect app.out == nothing advance duration("5s") expect app.exit == TimeoutExpired {} } } } ``` | Declaration | Scope and rule | |---|---| | `lab ` | Verification corpus for the unit's App; same-named fragments merge across source files | | Direct `scenario ` | Runs in the implicit simulation named after its Lab | | `simulation ` | Optional group with shared mocks; omission of a target selects the App | | `simulation : App` | Explicit App target; `app` and the App graph's declared name also work | | `mock ` | Names an actual Connector: a child of the App root directly, or a top-level declaration by its name | | `scenario ` | Independent run with its own mocks, origin and actions; the name carries its intent | | Mock override | Replaces the whole mock for that Connector: scenario, then simulation, then Lab | | Unit-level `val` | Available in mocks, injections, expectations and durations; Graph-local bindings do not escape into the Lab | A unit has one logical Lab. Duplicate scenarios or mocks at one level refuse. An explicit simulation cannot use its Lab's name when the Lab also contains direct scenarios. The Lab is absent from the production package and semantic hash. Mocks do not add ports, change Contracts or supply application metadata fields that the graph never writes. ## Mock responses | Form | Meaning | |---|---| | `on in where predicate { ... }` | First matching request clause in source order | | `on in { ... }` | Catch-all request clause | | Closed or predicate `match` | Select one checked response branch, using the same dispatch rules as the graph | | Local `val` | Pure response computation | | `out = value`, `err = value` | Emit a frame only on a port that the resolved Contract exposes | | `exit = Case { ... }` | Emit the Contract's typed terminal; unique and last | | `out = nothing` with no terminal | Explicit silence: leave the Call awaiting its deadline | Each non-silent Call response has exactly one final `exit` and exactly the frames that terminal requires. `rastok check` refuses a branch that omits a required frame or adds a forbidden one when its terminal is a case constructor. A computed terminal keeps the same check at execution. A Session response can emit frames without ending the resource; an optional exit remains last. For Process service, that terminal closes the mock child, not an individual conversation turn. An uncovered request or mock evaluation fault fails the scenario. Mocks are request-driven and stateless. Call mocks can select responses from the request and `now()`: [Two tenants](/examples/03-two-tenants.md) selects silence for Alice at the epoch, then responds after the time advance. For each Call, including a Retry attempt, `now()` is the civil timestamp at that Call's opening: the scenario's origin plus its logical opening instant, not the target of the surrounding `advance` or the first attempt's time. There is no authored mock invocation counter. `now()` is unavailable in Session mock bodies. Mock metadata writes, multi-emission statements and Loop commands refuse. ## Secrets in the Lab A mock replaces the external response, not request preparation. A Connector with `secret("logical/reference")` still needs a resolved deployment binding to seal its request. Use synthetic material for a simulation, not a production credential. The profile names the variable and its attested version, never the secret value. For example, the secret entry in `examples/webhook-to-partner.deployment.json` is: ```json { "reference": "showcase/partner/token", "environment": "RASTOK_SHOWCASE_PARTNER_TOKEN", "version": "fixture-v1" } ``` This entry belongs in the profile's `secrets` array. The example's complete profile also supplies its URL and data-policy declarations. From the repository root, run it with a synthetic value and the matching `_VERSION` variable: ```sh RASTOK_SHOWCASE_PARTNER_TOKEN=lab-only-not-a-credential \ RASTOK_SHOWCASE_PARTNER_TOKEN_VERSION=fixture-v1 \ rastok simulate examples/webhook-to-partner.rkg \ --deployment examples/webhook-to-partner.deployment.json ``` A missing binding names the Connector setting and asks for `--deployment`. A missing environment value names its variable; a missing or different attested version keeps the version-mismatch refusal. Secret material is not printed in either message. ## Actions | Action | Effect | |---|---| | `app.in = value` | Admit an input through a declared App input | | `listener.out = value` | Supply a decoded HttpServer `ack` request through its source model | | Injection followed by `seq N` | Choose the explicit nonnegative ingress sequence instead of the fixture counter | | `advance duration("5s")` | Move the logical timeline and process due obligations without sleeping five seconds | | `origin = timestamp("2026-10-30T12:00:00Z")` | Set the immutable civil anchor for this scenario; it is a declaration, not an action | Time starts at logical zero; the default civil origin is the Unix epoch. The origin affects `now()` and conversion of epoch-aligned slot bounds, not the graph hash. An advance uses a constant duration and cannot move time backwards. Each action settles ready work before the next expectation. Ready Call mock replies settle at the Call's opening instant. Resident Process Session mock replies settle at the instant of the input they answer. Their consequences run before the next deadline, so one large advance and several smaller advances deliver the same responses at the same instants. Injection targets are not arbitrary intermediate ports. Source injection models a decoded request, not malformed wire bytes or failed bearer authentication. Those refusals need Driver tests. WebSocket and Process Session test fixtures use their declared Session model and correlation metadata; they do not fabricate a Call per frame. Authored WebSocket Session mocks are not executable and refuse at check with `E-CHECK-DEFERRED`. See the capability distinctions in [Standard contracts](/reference/contracts.md). ## Expectations and windows | Form | Assertion | |---|---| | `expect target.port` | Exactly one observation | | `expect N target.port` | Exactly `N` observations, including zero | | `expect target.port == nothing` | No observations | | `expect [N] target.port == value` | Exactly `N` observations equal to the value; default one | | `expect [N] target.port where predicate` | Exactly `N` matching observations; default one | Square brackets in this table denote an optional count, not literal syntax. Counts are nonnegative integers. A nonzero count with `== nothing` refuses; zero with any other equality value also refuses. Use `expect 0 target.port where predicate` to require no matching observation. Equality uses the ordinary value grammar: scalars, records, tagged cases, maps, frontends and envelope fields. Values are checked against the observed port type. A complete data value compares structurally; an envelope pattern without a whole `data` assignment compares only its written fields. If a port or field has type `decimal`, an expectation of `7` matches `7u` and `decimal("7.00")` as well. The journal keeps the value as received. Predicates are checked over the observed port type; narrow a `variant` before reading its fields. An evaluation fault is a scenario fault, not a non-match. A newline after the port ends the expectation. An injection or time advance opens a new observation window. All following expectations inspect that window without consuming it; earlier windows are excluded. An emission appears once at its source, even if routed to `nothing`. `app.` observes an actual App-boundary crossing. Expectations do not inspect private Operator state or a mailbox. With Retry, an expectation on the Connector's own `exit` observes the terminal of every attempt, because each attempt is a journal fact. The graph downstream receives only the last one: assert the delivered outcome on the consumer's port. A repeated attempt does not appear on `.in`; the request is admitted once. ## Golden traces ```sh rastok simulate examples/echo.rkg rastok simulate examples/echo.rkg --compare examples/traces/echo rastok simulate examples/echo.rkg --save examples/traces/echo ``` | Option | Result | |---|---| | Neither | Run scenario expectations without consulting reference traces | | `--compare ` | Compare with stored traces, without modifying them | | `--save ` | Write or replace reference traces for intentional review | | Both | Usage error | | `--ui` | Inspect simulation boundaries and run them step by step in the debugger (requires a `hosted-ui` build) | Each file is `..rkc`. The stored format is deterministic CBOR rendered as one lowercase hexadecimal line per causal record, followed by `seal `. The seal covers concatenated record bytes. It excludes unsealed observations, such as host timing, but includes a handler's explicit observation of `now()`. A comparison reports the first divergent record, expected and obtained values, and causal context. For classified data, displayed details are masked while the comparison still uses the canonical bytes. A golden trace is distinct from the diagnostic recording produced by `run --record`: `replay` reconstructs recorded facts without calling a Driver again. A timestamp, duration or null can already travel as a whole payload in the Lab. For example, `expect app.wait == duration("5s")` compares the duration, not its printed spelling. A mock receives the value the graph sent. On a Process JSONL output or an untyped HttpClient JSON response, its output crosses the same JSON boundary as the Driver's: an object arrives as a map. Use `data as? Receipt` to read that object as a declared struct. A typed HttpClient mock supplies the decoded value. To model an invalid response body, write, for example, `exit = DecodeFailed { message = "response field out.due expects timestamp" }`. A handler can read `data.message` after testing `data is DecodeFailed`. ## Specified, not shipped | Item | Specification | |---|---| | Sub-graph simulation targets other than `app` | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §2 | | Delayed mock `after` actions | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §§3, 5.1; [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), mock grammar | | Scenario `crash node` and `restart node` | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §5.4 | | HttpServer `respond` source scripting; delayed/unsolicited Process service scripts | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §§2, 5.1 | | Mocks for WebSocket Sessions (refused at check with `E-CHECK-DEFERRED`) | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §2 | | Positive `expect fault` and assertions on private state | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §5.2 | | Automatic outcome coverage, generated scenarios and tags | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §§7–8 | | Production-to-scenario extraction | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §9 | | Experiments and theorems | [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md) §§10–11 | Sources: [`docs/spec/simulation-semantics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/simulation-semantics.md), [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), the checked scenario tree and the CLI trace writer. The guided walkthrough is [The Lab: scenarios, mocks and time](/guide/04-the-lab.md). --- --- title: "Agent gateway: keep a conversation isolated" description: Connect WebSocket conversations to resident JSONL processes, simulate interleaved app-server requests, and close one child without interrupting the other. url: https://docs.rastok.com/examples/06-agent-gateway source_revision: v0.2.0-alpha --- # Agent gateway: keep a conversation isolated This program connects each conversation to its own resident process and routes its replies to the right client. The sensor chapter kept state while time passed. A conversation adds state outside the graph: the memory of a child process. Alice and Bob should each keep their own child across several turns. Ending Alice's child must not interrupt Bob, and sending a message must not be mistaken for receiving an answer. The [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for the program and Lab, `.rkc` for a reviewed scenario reference and `.rkr` for a real execution recording. ## Run From the repository root, with `rastok` built with `hosted-ui` for the browser command (the non-browser command below does not need that feature): ```sh rastok simulate examples/agent-gateway.rkg --compare examples/traces/agent-gateway --ui ``` The debugger starts paused in the source view. Follow one input with **Next transition** and watch the source marker. Hover a port identifier, or focus it with Tab, to inspect its recorded value and open the full object in the inspector. The instance and Session tables show the recorded ownership. The **Graph** pane below the inspector follows connections while the source stays visible on the left. Selecting a node selects its source definition and inspector context. Both dividers are adjustable. **Fit graph** shows the complete drawing; **Readable size** restores interface-sized text with panning. Instance sections show counts and keep empty sections folded. For the reproducible CLI check: ```sh rastok simulate examples/agent-gateway.rkg --compare examples/traces/agent-gateway ``` ```text PASS app_server.two_conversations PASS app_server.unknown_method 2 scenario(s), 0 failed ``` For the controls and source view, see [the debugger tour](/debugger.md). ## Read the program Start at `clients.out` on the [WebSocketServer](/reference/connectors/websocket-server.md): each message enters `conversation`, where `instance = { key = meta.ext.session_id }` scopes its children. The first message opens [Process](/reference/connectors/process.md) with `mode = service`; later messages write to the same child. Each `route_reply` instance remembers its socket address and restores it on that child's responses. The real command is `codex app-server --listen stdio://`. The client, not Process, speaks its JSON-RPC protocol: initialize, acknowledge initialization, start a thread, send a turn. Requests, replies and notifications pass through as JSON, including client replies without a `method` field. The Lab's `match` replaces the child; it never launches Codex. Its `peer` input supplies the scenario's incoming messages. Follow `finish.out -> model.instance.stop` last. An authored `close` input requests that exact child generation's Closing, not every Process or the whole conversation Graph. Socket closure has its own `session_exit` output. The [Lab reference](/reference/lab.md) explains mock responses, expectations and observation windows. `advance` supplies virtual time; a mock's terminal response ends its simulated exchange, not the whole scenario. Source: `examples/agent-gateway.rkg` ```rkg // One local WebSocket conversation owns one resident JSONL process. // Clients speak the Codex app-server protocol: initialize, initialized, // thread/start, then turn/start. The Lab never launches Codex. val alice_session = "11111111111111111111111111111111" val bob_session = "22222222222222222222222222222222" val thread_id = "thread-1" type JsonObject = map graph agent_gateway : App { // Public fixture ingress; real clients enter through clients.out instead. input peer: variant input close: variant output reply: variant output process_exit: ProcessExit output session_exit: variant connector clients : WebSocketServer { listen = "127.0.0.1:8443" path = "/agent" codec = json handshake_timeout = duration("5s") max_message = "1MiB" correlate = meta.ext.session_id versions = ["http/1.1"] } graph conversation { input in: variant input close: variant output out: variant output exit: ProcessExit instance = { key = meta.ext.session_id } lifetime = { kind = idle; max = duration("5m") } closing = { drain_for = duration("1s"); settle_for = duration("1s") } connector model : Process { mode = service command = "codex" args = ["app-server", "--listen", "stdio://"] codec = jsonl max_frame = "1MiB" behavior = probabilistic closing = { drain_for = duration("1s"); settle_for = duration("1s") } } operator route_reply { input remember: variant input in: variant output out: variant var socket: string = "" // Admission queues remember before child replies can be routed here. // This state belongs to this conversation, not a global last-request slot. on remember { socket = meta.ext.session_id as string } on in { out = { data = data; meta.ext.session_id = socket } } } operator finish { input in: variant output out: variant on in { out = . } } in -> model in -> route_reply.remember close -> finish finish.out -> model.instance.stop model.out -> route_reply -> out model.err -> nothing model.exit -> exit } clients.out -> conversation peer -> conversation close -> conversation.close conversation.out -> { clients.in; reply } conversation.exit -> process_exit // Closing a socket is observable, not an implicit process cancellation. // The idle lifetime bounds abandoned conversations independently. clients.exit -> session_exit } lab app_server { mock conversation.model { // Actual JSON objects are maps, not DSL struct literals. // This fixture's client frames all have the protocol's method field. on in where data is JsonObject { match { data.?method == "initialize" => out = { "id": data.?id, "result": { "userAgent": "scripted-codex" } } data.?method == "initialized" => nothing data.?method == "thread/start" => out = { "id": data.?id, "result": { "thread": { "id": thread_id } } } data.?method == "turn/start" => { val turn_id = "turn-1" out = { "id": data.?id, "result": { "turn": { "id": turn_id, "status": "inProgress" } } } out = ({ "method": "item/agentMessage/delta", "params": { "threadId": thread_id, "turnId": turn_id, "itemId": "item-1", "delta": "Hello from the simulated agent." } }) out = ({ "method": "turn/completed", "params": { "threadId": thread_id, "turn": { "id": turn_id, "status": "completed" } } }) } data.?method == "turn/interrupt" => out = { "id": data.?id, "result": {:} } _ => out = { "id": data.?id, "error": { "code": -32601, "message": "scripted method unavailable" } } } } on in { out = nothing } } scenario two_conversations { app.peer = { meta.ext.session_id = alice_session; data = { "id": 0, "method": "initialize", "params": { "clientInfo": { "name": "rastok_gallery", "version": "1" } } } } expect app.reply where meta.ext.session_id == alice_session app.peer = { meta.ext.session_id = bob_session; data = { "id": 0, "method": "initialize", "params": { "clientInfo": { "name": "rastok_gallery", "version": "1" } } } } expect app.reply where meta.ext.session_id == bob_session app.peer = { meta.ext.session_id = alice_session; data = { "method": "initialized" } } expect app.reply == nothing app.peer = { meta.ext.session_id = bob_session; data = { "method": "initialized" } } app.peer = { meta.ext.session_id = alice_session; data = { "id": 1, "method": "thread/start", "params": { "approvalPolicy": "never", "sandbox": "read-only" } } } expect app.reply app.peer = { meta.ext.session_id = bob_session; data = { "id": 1, "method": "thread/start", "params": { "approvalPolicy": "never", "sandbox": "read-only" } } } expect app.reply app.peer = { meta.ext.session_id = alice_session; data = { "id": 2, "method": "turn/start", "params": { "threadId": thread_id, "input": [{ "type": "text", "text": "Hello Alice" }] } } } expect 3 app.reply where meta.ext.session_id == alice_session expect app.process_exit == nothing app.peer = { meta.ext.session_id = bob_session; data = { "id": 2, "method": "turn/start", "params": { "threadId": thread_id, "input": [{ "type": "text", "text": "Hello Bob" }] } } } expect 3 app.reply where meta.ext.session_id == bob_session app.close = { meta.ext.session_id = alice_session; data = "operator requested shutdown" } advance duration("2s") expect app.process_exit where data is OutcomeUnknown app.peer = { meta.ext.session_id = bob_session; data = { "id": 3, "method": "turn/start", "params": { "threadId": thread_id, "input": [{ "type": "text", "text": "Still here?" }] } } } expect 3 app.reply where meta.ext.session_id == bob_session expect app.process_exit == nothing } scenario unknown_method { app.peer = { meta.ext.session_id = alice_session; data = { "id": 0, "method": "fixture/unknown", "params": {:} } } expect app.reply expect app.process_exit == nothing } } ``` ## Expected result This cut of `app_server.two_conversations` starts after both initialization and thread exchanges. The Lab enters through `peer`, not a real socket; each reply also targets `clients.in`, omitted here to focus on isolation. ```mermaid sequenceDiagram participant lab as Lab: app_server.two_conversations participant app as agent_gateway participant model as conversation.model: Process service participant route as conversation.route_reply participant finish as conversation.finish Note over model,route: Separate instances keyed by session_id loop Alice, then Bob, in recorded order lab->>app: peer = turn/start, id 2, session_id app->>model: in = turn/start for this session app->>route: remember = this session_id model->>lab: Scripted service input lab-->>model: Response, delta, turn/completed model->>route: Three out frames in that order route-->>app: Three reply frames addressed to this session end lab->>app: close = Alice's session app->>finish: in = close request finish->>model: Alice: instance.stop lab->>lab: advance 2s model-->>app: process_exit = OutcomeUnknown for Alice lab->>app: peer = Bob's turn/start, id 3 Note over model,route: Bob's original service returns three addressed replies ``` Alice and Bob both initialize and start a thread. Both use request ids 0, 1 and 2: isolation cannot rely on globally unique RPC ids. Each scripted turn returns an initial response, a text delta and a final notification. Two resources serve the conversation, not one process per message. Alice's stop settles as `OutcomeUnknown` because the mock supplies no system-shutdown observation. Bob's next turn still uses his original child. The second scenario returns a scripted unknown-method error. It is JSON data, not a Process `exit`. The separate resident primer, [agent-dialogue.rkg](/examples/agent-dialogue.rkg), shows an application `quit`, observed resource exit and a fresh resource on new input. Its real child, `cat`, echoes a JSON line with `tenant` and `text`. The adapter reads the object with `as? Message` and puts the text in the reply's `answer` field. Only the Lab supplies the scripted conversation. With `cat` on PATH, run the primer interactively: ```sh rastok run examples/agent-dialogue.rkg ``` Type `hello from cat` and press Enter. The real reply is: ```text out: {"answer":"hello from cat","tenant":"local"} ``` Each line uses the same local session. Press Ctrl-C to stop it. To run the scripted conversations instead, use the same traces directory as the gateway: ```sh rastok simulate examples/agent-dialogue.rkg --compare examples/traces/agent-gateway ``` ```text PASS scripted_model.alice_and_bob PASS scripted_model.fresh_child 2 scenario(s), 0 failed ``` To break just this primer, change `text = "Plant tomatoes."` in the mock to `text = "Plant carrots."`. Leave the expectations and reference traces alone: ```sh rastok simulate examples/agent-dialogue.rkg --compare examples/traces/agent-gateway ``` ```text FAIL scripted_model.alice_and_bob expect app.out where data.tenant == "alice" && data.answer == "Plant tomatoes." (agent-dialogue.rkg:95) observed app.out: {"answer":"Plant carrots.","tenant":"alice"} where data.tenant == "alice" && data.answer == "Plant tomatoes." is false for 1 of 1 deliveries; count 0, expected 1 golden divergence: record 10: envelope(8) . data(5)[1] (ccbor value)[1][0][1][1]; expected "Plant tomatoes."; got "Plant carrots."; cause: INGRESS "conversation.model" · port "out" · sequence 0 FAIL scripted_model.fresh_child golden divergence: record 10: envelope(8) . data(5)[1] (ccbor value)[1][0][1][1]; expected "Plant tomatoes."; got "Plant carrots."; cause: INGRESS "conversation.model" · port "out" · sequence 0 2 scenario(s), 2 failed ``` The first scenario expected the original answer. The second checks that an answer arrives, but its reference trace also checks which answer it was. Restore the example before continuing; this discards your edit to this file: ```sh git checkout -- examples/agent-dialogue.rkg ``` ## Add the small browser client The next step is [Rastok Codex Gateway](/examples/agent-chat.rkg), with a single [readable HTML file](https://github.com/rastok-io/rastok/blob/2e5128c76faf35cc879211138f429a4048608c77/examples/agent-chat.html). It uses plain HTML, CSS and JavaScript, with English comments: no framework, build step, CDN or generated bundle. Start with its scripted protocol: ```sh rastok simulate examples/agent-chat.rkg ``` ```text PASS browser_protocol.alice_and_bob PASS browser_protocol.duplicate_name PASS browser_protocol.invalid_message 3 scenario(s), 0 failed ``` Three scenarios cover interleaved conversations, a duplicate nickname and invalid messages. The same app-server handshake is now wrapped in `{ nickname, kind, rpc }`. `conversation` is keyed by the nickname and remembers its socket; a second socket cannot take that name or close its child. The Lab still enters through `peer`, without binding either network listener. For the real local application, use a macOS or Linux shell and install and configure Codex on PATH first. Live account-dependent output is not quoted here: the documented checks run only the Lab. This command **does launch real processes** when a client connects, and sending a message may use your configured model/account: ```sh cargo run -p rastok --features hosted-websocket -- run examples/agent-chat.rkg ``` Open `http://127.0.0.1:8777/`, connect as Alice, and open another tab for Bob. Send a message in each, then choose **Quit** for Alice and continue with Bob. The page waits for `turn/completed`, not just the initial `turn/start` reply, before enabling the next message. Model text is rendered literally, not as HTML. An unsupported server-initiated request is explicitly declined. The two flows share an App, not a transaction. `page` serves the embedded `asset(...)` through [HttpServer](/reference/connectors/http-server.md); `clients` carries chat over WebSocket at `127.0.0.1:8778/chat`. Neither listener is inside the keyed conversation. The current cooperative Worker can keep serving the page and other children while external I/O waits; this does not claim parallel DSL execution. Quit is an application message routed to `instance.stop` **inside that conversation**. It closes the conversation and its children, not the App or Bob. It is never a magic line sent to Codex's stdin. The acknowledgement means “closure requested”, not “the child exited successfully”. Closing a browser tab without Quit is different: the abandoned conversation has a five-minute idle lifetime. This page has no reconnect/resume feature or saved history. It sends `ephemeral: true` on each `thread/start`: new Codex conversations stay in memory instead of being saved as local thread history. This option is part of the [app-server protocol](https://learn.chatgpt.com/docs/app-server), not a Process flag. It does not delete earlier histories or disable technical logs, Rastok's in-memory journal, or the model provider's data retention. Quit still requests process closure, not deletion of files. The page selects the app-server read-only sandbox and no-approval policy; this is a trusted local example, not a security boundary. Do not expose the listeners publicly or send credentials through the chat. Editing the HTML changes its embedded asset: restart `run` to load the new file. ## Inspect a typed model response The [HTTP model adapter](/examples/08-model-adapter.md) makes one non-streaming OpenAI Responses request per job. It selects a typed JSON response, retains original usage samples with their job and session, and distinguishes missing usage from an observed zero. Its six scenarios run with synthetic boot bindings. Use that chapter for the reproducible command, projected-schema rules, secret boundary and golden comparison. A resident process preserves a conversation across messages; this adapter sends independent jobs and does not retry an inference that could be charged twice. ## Break it Change only `Hello from the simulated agent.` to `A different answer.` in the mock. Leave the golden unchanged and run the comparison below. The graph still compiles, and the shape/count assertions still pass. The changed answer nevertheless differs in the recorded evidence. ```sh rastok simulate examples/agent-gateway.rkg --compare examples/traces/agent-gateway ``` ```text FAIL app_server.two_conversations golden divergence: record 51: envelope(8) . data(5)[1] (ccbor value)[1][1][1][1][0][1][1]; expected "Hello from the simulated agent."; got "A different answer."; cause: INGRESS "conversation.model" · port "out" · sequence 5 PASS app_server.unknown_method 2 scenario(s), 1 failed ``` Restore the checked-in source (this discards your edits to this example): ```sh git checkout -- examples/agent-gateway.rkg ``` ## Read the golden difference The diff names the first changed record, expected and actual data, and the recorded cause. Here the changed evidence is an inbound service frame, not an invented per-turn Call completion. Do not use `--save` to hide the change. Restore the answer before continuing.
Inspect the raw sealed trace (.rkc) The versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence. Source: `examples/traces/agent-gateway/app_server.two_conversations.rkc` ```rastok-trace a7070108a50150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582025869821083828206626964820200828206666d6574686f6482066a696e697469616c697a6582820666706172616d738210818282066a636c69656e74496e666f821082828206646e616d6582066e726173746f6b5f67616c6c6572798282066776657273696f6e82066131068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313109636c61620a000b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100 a7070211601282438280800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8 a80702116c636f6e766572736174696f6e1282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c81822824382808000 a807021172636f6e766572736174696f6e2e6d6f64656c1282584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100 a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100 a70702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d6265728243828080000116818266736f636b65748206782031313131313131313131313131313131313131313131313131313131313131311780 a20703182585015060f0ea2e346639561873c38cc146c4e550f3df1105112054d397a04ed0666ca4c872636f6e766572736174696f6e2e6d6f64656c5820310e5f8777e8a955077d59025cbf16dd436689f888e710ef8cff288a13053788 a20703182583025060f0ea2e346639561873c38cc146c4e572636f6e766572736174696f6e2e6d6f64656c a9070108a50150362854cc809d77e8494e9a5dabf4bbe20350362854cc809d77e8494e9a5dabf4bbe20401058202583782108282820662696482020082820666726573756c7482108182820669757365724167656e7482066e73637269707465642d636f646578068183636578746a73657373696f6e5f69648206782036306630656132653334363633393536313837336333386363313436633465350972636f6e766572736174696f6e2e6d6f64656c0a000b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131000e82025060f0ea2e346639561873c38cc146c4e50f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310001178183636f757400a6015061829718361a64aa02209a504448618d0250362854cc809d77e8494e9a5dabf4bbe20350362854cc809d77e8494e9a5dabf4bbe20401058202583782108282820662696482020082820666726573756c7482108182820669757365724167656e7482066e73637269707465642d636f646578068183636578746a73657373696f6e5f6964820678203131313131313131313131313131313131313131313131313131313131313131181881820850c5bb442dc34dbd29f39a6dd93aba1f3a181981835061829718361a64aa02209a504448618d7827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a807021167636c69656e747312824b828167636c69656e7473800013676c3a737461727414801780181a5061829718361a64aa02209a504448618d1822824382808000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100011780181a5061829718361a64aa02209a504448618d a7070108a50150e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd04010582025869821083828206626964820200828206666d6574686f6482066a696e697469616c697a6582820666706172616d738210818282066a636c69656e74496e666f821082828206646e616d6582066e726173746f6b5f67616c6c6572798282066776657273696f6e82066131068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323209636c61620a010b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200 a80702116c636f6e766572736174696f6e1282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd1822824382808000 a807021172636f6e766572736174696f6e2e6d6f64656c1282584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd182282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200 a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd182282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200 a70702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d6265728243828080000216818266736f636b65748206782032323232323232323232323232323232323232323232323232323232323232321780 a20703182585015028ca2e2364d3761195c1858dc8f48b0250e6c20d6146234b74a33da1c709e86efd72636f6e766572736174696f6e2e6d6f64656c5820310e5f8777e8a955077d59025cbf16dd436689f888e710ef8cff288a13053788 a20703182583025028ca2e2364d3761195c1858dc8f48b0272636f6e766572736174696f6e2e6d6f64656c a9070108a50150da26c6766ce89f38556f36b29c85d8600350da26c6766ce89f38556f36b29c85d8600401058202583782108282820662696482020082820666726573756c7482108182820669757365724167656e7482066e73637269707465642d636f646578068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a010b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320001178183636f757400a60150a6a9a6aa373d0ad52606aba55efd822b0250da26c6766ce89f38556f36b29c85d8600350da26c6766ce89f38556f36b29c85d8600401058202583782108282820662696482020082820666726573756c7482108182820669757365724167656e7482066e73637269707465642d636f646578068183636578746a73657373696f6e5f69648206782032323232323232323232323232323232323232323232323232323232323232321818818208500f26f577b136b33c00af37544808d3761819818350a6a9a6aa373d0ad52606aba55efd822b7827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200011780181a50a6a9a6aa373d0ad52606aba55efd822b a7070108a501506c793d2fff3f39818152c34ffedee98103506c793d2fff3f39818152c34ffedee9810401058202581b821081828206666d6574686f6482066b696e697469616c697a6564068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313109636c61620a020b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100 a60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000031780 a20703182586035060f0ea2e346639561873c38cc146c4e550dfc724074306fa8e15132b42ebd3c211506c793d2fff3f39818152c34ffedee98172636f6e766572736174696f6e2e6d6f64656c5820a5b8f3e7598201ae7ece5b18fa12780e91f4fa6d00d63228263653fdcd4533a6 a20703182584045060f0ea2e346639561873c38cc146c4e550dfc724074306fa8e15132b42ebd3c21172636f6e766572736174696f6e2e6d6f64656c a7070108a501501f48ee4d457e9526b70a88345813643a03501f48ee4d457e9526b70a88345813643a0401058202581b821081828206666d6574686f6482066b696e697469616c697a6564068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323209636c61620a030b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200 a60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000041780 a20703182586035028ca2e2364d3761195c1858dc8f48b0250403609522b50139cd9e5f70500a46d24501f48ee4d457e9526b70a88345813643a72636f6e766572736174696f6e2e6d6f64656c5820a5b8f3e7598201ae7ece5b18fa12780e91f4fa6d00d63228263653fdcd4533a6 a20703182584045028ca2e2364d3761195c1858dc8f48b0250403609522b50139cd9e5f70500a46d2472636f6e766572736174696f6e2e6d6f64656c a7070108a501507a1dc07e4137d05e725f8902f4c53a6b03507a1dc07e4137d05e725f8902f4c53a6b04010582025863821083828206626964820201828206666d6574686f6482066c7468726561642f737461727482820666706172616d738210828282066773616e64626f78820669726561642d6f6e6c798282066e617070726f76616c506f6c6963798206656e65766572068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313109636c61620a040b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100 a60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000051780 a20703182586035060f0ea2e346639561873c38cc146c4e55023f9925781f33c8606191c249d91a336507a1dc07e4137d05e725f8902f4c53a6b72636f6e766572736174696f6e2e6d6f64656c5820785cb53ea440f6bb44f2ff148bde2eea8996a1dcf8278c576b0142d24536b506 a20703182584045060f0ea2e346639561873c38cc146c4e55023f9925781f33c8606191c249d91a33672636f6e766572736174696f6e2e6d6f64656c a9070108a50150d85cab4a77515fa815eeda088b0d8e7d0350d85cab4a77515fa815eeda088b0d8e7d0401058202583782108282820662696482020182820666726573756c74821081828206667468726561648210818282066269648206687468726561642d31068183636578746a73657373696f6e5f69648206782036306630656132653334363633393536313837336333386363313436633465350972636f6e766572736174696f6e2e6d6f64656c0a020b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131000e82025060f0ea2e346639561873c38cc146c4e50f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310002178183636f757400a60150a48c7eae647650d39d1353c60e88253c0250d85cab4a77515fa815eeda088b0d8e7d0350d85cab4a77515fa815eeda088b0d8e7d0401058202583782108282820662696482020182820666726573756c74821081828206667468726561648210818282066269648206687468726561642d31068183636578746a73657373696f6e5f69648206782031313131313131313131313131313131313131313131313131313131313131311818818208509bf911312c93486a11872119b36378221819818350a48c7eae647650d39d1353c60e88253c7827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100021780181a50a48c7eae647650d39d1353c60e88253c a7070108a501505a65c55dbdea6f2f6195918a7014326703505a65c55dbdea6f2f6195918a7014326704010582025863821083828206626964820201828206666d6574686f6482066c7468726561642f737461727482820666706172616d738210828282066773616e64626f78820669726561642d6f6e6c798282066e617070726f76616c506f6c6963798206656e65766572068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323209636c61620a050b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200 a60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000061780 a20703182586035028ca2e2364d3761195c1858dc8f48b0250965c529effe97365ee48d403c8eaea9d505a65c55dbdea6f2f6195918a7014326772636f6e766572736174696f6e2e6d6f64656c5820785cb53ea440f6bb44f2ff148bde2eea8996a1dcf8278c576b0142d24536b506 a20703182584045028ca2e2364d3761195c1858dc8f48b0250965c529effe97365ee48d403c8eaea9d72636f6e766572736174696f6e2e6d6f64656c a9070108a5015070263ee695d6f82fe6b7eaab5cdb6df8035070263ee695d6f82fe6b7eaab5cdb6df80401058202583782108282820662696482020182820666726573756c74821081828206667468726561648210818282066269648206687468726561642d31068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a030b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320002178183636f757400a60150094928430ad3dc030db4357d5def6b60025070263ee695d6f82fe6b7eaab5cdb6df8035070263ee695d6f82fe6b7eaab5cdb6df80401058202583782108282820662696482020182820666726573756c74821081828206667468726561648210818282066269648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323218188182085007dc03a8a0f441b692274fb0d231e8fc1819818350094928430ad3dc030db4357d5def6b607827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200021780181a50094928430ad3dc030db4357d5def6b60 a7070108a5015094300aa39de9b2df8c605fb45942949c035094300aa39de9b2df8c605fb45942949c0401058202587b821083828206626964820202828206666d6574686f6482066a7475726e2f737461727482820666706172616d7382108282820665696e707574821181821082828206647465787482066b48656c6c6f20416c6963658282066474797065820664746578748282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313109636c61620a060b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100 a60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000071780 a20703182586035060f0ea2e346639561873c38cc146c4e55036d97cb49e6b2dda7be724dfab872b3b5094300aa39de9b2df8c605fb45942949c72636f6e766572736174696f6e2e6d6f64656c58207c3a3a080b7bf40552e42561101343021e13c7961cd2844df0f65f5b55320018 a20703182584045060f0ea2e346639561873c38cc146c4e55036d97cb49e6b2dda7be724dfab872b3b72636f6e766572736174696f6e2e6d6f64656c a9070108a501508399157fc1ce3bee3b71ecc12416c3c503508399157fc1ce3bee3b71ecc12416c3c50401058202584a82108282820662696482020282820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f69648206782036306630656132653334363633393536313837336333386363313436633465350972636f6e766572736174696f6e2e6d6f64656c0a040b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131000e82025060f0ea2e346639561873c38cc146c4e50f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310003178183636f757400a601505ee43032f78c7dee057dd08e02fc9bb602508399157fc1ce3bee3b71ecc12416c3c503508399157fc1ce3bee3b71ecc12416c3c50401058202584a82108282820662696482020282820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f69648206782031313131313131313131313131313131313131313131313131313131313131311818818208501defae7990bb311da534ab1f1bca309518198183505ee43032f78c7dee057dd08e02fc9bb67827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100031780181a505ee43032f78c7dee057dd08e02fc9bb6 a9070108a50150a599ab8b09d1ad42b0da4db66542d37d0350a599ab8b09d1ad42b0da4db66542d37d0401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782036306630656132653334363633393536313837336333386363313436633465350972636f6e766572736174696f6e2e6d6f64656c0a050b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131000e82025060f0ea2e346639561873c38cc146c4e50f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310004178183636f757400a601504d002ed62c923755160e6b980fdf22690250a599ab8b09d1ad42b0da4db66542d37d0350a599ab8b09d1ad42b0da4db66542d37d0401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313118188182085025a18503ead56bea58a1b80afd84973b18198183504d002ed62c923755160e6b980fdf22697827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100041780181a504d002ed62c923755160e6b980fdf2269 a9070108a5015021da703c80ac8a5699477d71967da0af035021da703c80ac8a5699477d71967da0af04010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782036306630656132653334363633393536313837336333386363313436633465350972636f6e766572736174696f6e2e6d6f64656c0a060b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131000e82025060f0ea2e346639561873c38cc146c4e50f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310005178183636f757400a601503476f939f976804bdd24cdae240e2429025021da703c80ac8a5699477d71967da0af035021da703c80ac8a5699477d71967da0af04010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f6964820678203131313131313131313131313131313131313131313131313131313131313131181881820850fdb891ba72f9e5aa9f7f5476315a524d18198183503476f939f976804bdd24cdae240e24297827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100051780181a503476f939f976804bdd24cdae240e2429 a7070108a5015091784c371eafa12dd3f5b1371b9a99f0035091784c371eafa12dd3f5b1371b9a99f004010582025879821083828206626964820202828206666d6574686f6482066a7475726e2f737461727482820666706172616d7382108282820665696e707574821181821082828206647465787482066948656c6c6f20426f628282066474797065820664746578748282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323209636c61620a070b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200 a60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000081780 a20703182586035028ca2e2364d3761195c1858dc8f48b02509c4837ed8dfb86e0e9a0c105e53199b45091784c371eafa12dd3f5b1371b9a99f072636f6e766572736174696f6e2e6d6f64656c5820b97e7d53bbbee50dca746a05483d53e494dc56b1494fd6e6a0253dc8c0f36dfe a20703182584045028ca2e2364d3761195c1858dc8f48b02509c4837ed8dfb86e0e9a0c105e53199b472636f6e766572736174696f6e2e6d6f64656c a9070108a501503667cc57f26972263806465fc521fbe303503667cc57f26972263806465fc521fbe30401058202584a82108282820662696482020282820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a070b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320003178183636f757400a601505ec01b153123b01b38bbe8bb56dcbc6902503667cc57f26972263806465fc521fbe303503667cc57f26972263806465fc521fbe30401058202584a82108282820662696482020282820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f69648206782032323232323232323232323232323232323232323232323232323232323232321818818208509609abe35466aef5d0e20a3b2a09193718198183505ec01b153123b01b38bbe8bb56dcbc697827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200031780181a505ec01b153123b01b38bbe8bb56dcbc69 a9070108a501503b5d783f2a2355c94fb177fcf3d821ce03503b5d783f2a2355c94fb177fcf3d821ce0401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a080b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320004178183636f757400a6015050dc87efbca589bd458fa9f86a8f606f02503b5d783f2a2355c94fb177fcf3d821ce03503b5d783f2a2355c94fb177fcf3d821ce0401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323218188182085072e0e9e05713400422e08d459e037131181981835050dc87efbca589bd458fa9f86a8f606f7827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200041780181a5050dc87efbca589bd458fa9f86a8f606f a9070108a501508e6d79deb010ca935813401a687af50903508e6d79deb010ca935813401a687af50904010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a090b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320005178183636f757400a60150a5ff7c92c54b7228552513b97c412fb002508e6d79deb010ca935813401a687af50903508e6d79deb010ca935813401a687af50904010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782032323232323232323232323232323232323232323232323232323232323232321818818208509069cd3f4fb01ad07bf4667928e1789f1819818350a5ff7c92c54b7228552513b97c412fb07827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200051780181a50a5ff7c92c54b7228552513b97c412fb0 a7070108a5015094e195b78473826cf0a323972a212aa9035094e195b78473826cf0a323972a212aa90401058202581f8206781b6f70657261746f72207265717565737465642073687574646f776e068183636578746a73657373696f6e5f696482067820313131313131313131313131313131313131313131313131313131313131313109636c61620a080b000c65636c6f73650d8182781d2e636c6f73653e636f6e766572736174696f6e2e66696e6973682e696e82584d82826c636f6e766572736174696f6e6666696e6973688183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100 a807021173636f6e766572736174696f6e2e66696e6973681282584d82826c636f6e766572736174696f6e6666696e6973688183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013676c3a737461727414801780181a5094e195b78473826cf0a323972a212aa9182282584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100 a707021173636f6e766572736174696f6e2e66696e6973681282584d82826c636f6e766572736174696f6e6666696e6973688183816c636f6e766572736174696f6e018207820678203131313131313131313131313131313131313131313131313131313131313131001364703a696e148183781d2e636c6f73653e636f6e766572736174696f6e2e66696e6973682e696e82438280800001178183636f757400a60150d3759ac2297936b27bd918838727504d025094e195b78473826cf0a323972a212aa9035094e195b78473826cf0a323972a212aa90401058202581f8206781b6f70657261746f72207265717565737465642073687574646f776e068183636578746a73657373696f6e5f6964820678203131313131313131313131313131313131313131313131313131313131313131182aa101818750a4b1d86f91e1de597d736278be92a8c102636f757482584d82826c636f6e766572736174696f6e6666696e6973688183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310082584682816c636f6e766572736174696f6e8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310082584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310050d3759ac2297936b27bd918838727504d aa07021172636f6e766572736174696f6e2e6d6f64656c1282584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013676c3a636c6f736514801780181882820550d72f675db802aa830f6374bb7429a2a282065034aa66a9f5e197b28bf2dd8617ff48f7181a50d3759ac2297936b27bd918838727504d182382584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e01820782067820313131313131313131313131313131313131313131313131313131313131313100182aa10250a4b1d86f91e1de597d736278be92a8c1 a807021172636f6e766572736174696f6e2e6d6f64656c1282584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013666c3a65786974148183781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82438280800001178183646578697400a60150d4cae196e843d14556fca9aea74f7d4b0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c80401058202558213826e4f7574636f6d65556e6b6e6f776e820f80068183636578746a73657373696f6e5f6964820678203630663065613265333436363339353631383733633338636331343663346535181a50f3df1105112054d397a04ed0666ca4c818245060f0ea2e346639561873c38cc146c4e5 a707021172636f6e766572736174696f6e2e6d6f64656c1282584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782031313131313131313131313131313131313131313131313131313131313131310013666c3a73746f7014801780181a50d3759ac2297936b27bd918838727504d a7070108a50150321cb79d91c55f2a83c1d37584dd2f380350321cb79d91c55f2a83c1d37584dd2f380401058202587b821083828206626964820203828206666d6574686f6482066a7475726e2f737461727482820666706172616d7382108282820665696e707574821181821082828206647465787482066b5374696c6c20686572653f8282066474797065820664746578748282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323209636c61620a090b000c64706565720d8282781b2e706565723e636f6e766572736174696f6e2e6d6f64656c2e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232008278272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d62657282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200 a60702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200136a703a72656d656d62657214818378272e706565723e636f6e766572736174696f6e2e726f7574655f7265706c792e72656d656d626572824382808000091780 a20703182586035028ca2e2364d3761195c1858dc8f48b02508511ed8e6b8d49da0a5d16c6d6b8c44250321cb79d91c55f2a83c1d37584dd2f3872636f6e766572736174696f6e2e6d6f64656c5820c509a007751ed335460b8922a8ba7313eeb6912c1d1f9cede6967109247ce768 a20703182584045028ca2e2364d3761195c1858dc8f48b02508511ed8e6b8d49da0a5d16c6d6b8c44272636f6e766572736174696f6e2e6d6f64656c a9070108a501502a83395156a623917280845d111cc5a603502a83395156a623917280845d111cc5a60401058202584a82108282820662696482020382820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a0a0b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320006178183636f757400a60150c38cc9bfe9be32cff8457bc345a7d38902502a83395156a623917280845d111cc5a603502a83395156a623917280845d111cc5a60401058202584a82108282820662696482020382820666726573756c74821081828206647475726e8210828282066269648206667475726e2d318282066673746174757382066a696e50726f6772657373068183636578746a73657373696f6e5f6964820678203232323232323232323232323232323232323232323232323232323232323232181881820850d1e75b558147897f7b4bd82b1c4d9f931819818350c38cc9bfe9be32cff8457bc345a7d3897827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200061780181a50c38cc9bfe9be32cff8457bc345a7d389 a9070108a50150ce4e269094360f9a1c8b9c74576f5b510350ce4e269094360f9a1c8b9c74576f5b510401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a0b0b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320007178183636f757400a601501b98e2416b21093f070c6cf001387f170250ce4e269094360f9a1c8b9c74576f5b510350ce4e269094360f9a1c8b9c74576f5b510401058202589d821082828206666d6574686f648206776974656d2f6167656e744d6573736167652f64656c746182820666706172616d738210848282066564656c74618206781f48656c6c6f2066726f6d207468652073696d756c61746564206167656e742e828206666974656d49648206666974656d2d31828206667475726e49648206667475726e2d318282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323218188182085057c519758af6dea6f51b43d92474a1a918198183501b98e2416b21093f070c6cf001387f177827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200071780181a501b98e2416b21093f070c6cf001387f17 a9070108a5015086e1114149d7e29d8d0ac4799c66ecf1035086e1114149d7e29d8d0ac4799c66ecf104010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f69648206782032386361326532333634643337363131393563313835386463386634386230320972636f6e766572736174696f6e2e6d6f64656c0a0c0b000c636f75740d81827832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232000e82025028ca2e2364d3761195c1858dc8f48b020f826c636f6e766572736174696f6e656d6f64656c a80702117818636f6e766572736174696f6e2e726f7574655f7265706c791282585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e018207820678203232323232323232323232323232323232323232323232323232323232323232001364703a696e1481837832636f6e766572736174696f6e2e6d6f64656c2e6f75743e636f6e766572736174696f6e2e726f7574655f7265706c792e696e82584c82826c636f6e766572736174696f6e656d6f64656c8183816c636f6e766572736174696f6e0182078206782032323232323232323232323232323232323232323232323232323232323232320008178183636f757400a601506da88fb766bd96c99f41468aaf1c92ae025086e1114149d7e29d8d0ac4799c66ecf1035086e1114149d7e29d8d0ac4799c66ecf104010582025872821082828206666d6574686f6482066e7475726e2f636f6d706c6574656482820666706172616d73821082828206647475726e8210828282066269648206667475726e2d3182820666737461747573820669636f6d706c657465648282066874687265616449648206687468726561642d31068183636578746a73657373696f6e5f696482067820323232323232323232323232323232323232323232323232323232323232323218188182085054bc77b81493d7958d6db5b269cbf4ea18198183506da88fb766bd96c99f41468aaf1c92ae7827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e824b828167636c69656e74738000 a707021167636c69656e747312824b828167636c69656e747380001364703a696e1481837827636f6e766572736174696f6e2e726f7574655f7265706c792e6f75743e636c69656e74732e696e82585282826c636f6e766572736174696f6e6b726f7574655f7265706c798183816c636f6e766572736174696f6e01820782067820323232323232323232323232323232323232323232323232323232323232323200081780181a506da88fb766bd96c99f41468aaf1c92ae seal 29b0c9ff02226074604d3b86f86f535d81d91d9e5edd1b6c857cecf45fdb0181 ```
## Carry forward Previous: [Sensor alarm](/examples/05-sensor-alarm.md). You now have the pieces to isolate an agent conversation: typed Contracts, instance-owned state, a resident resource, explicit shutdown, and a controlled external world. Try the standalone browser client above, or the smaller resident primer to add your own typed adapter. Model-specific usage evidence belongs at that adapter boundary, not in a protocol hidden inside Process. The HTTP variant above shows the typed boundary and retains the quantities declared by its response schema. Next: [Countdown](/examples/07-countdown.md), where a decreasing measure proves that authored recurrence finishes. ## Limits This is a trusted **local** bridge, not a public authenticated AI service. A real client owns handshake sequencing, request ids, approvals and the read-only tool policy. The teaching page requests read-only execution; that is not an authentication boundary or permission to expose it publicly. `behavior = probabilistic` describes the external boundary; the Lab remains deterministic. Tests compose real sockets with harmless shell children, not a model or a credential. Process has no `secret()` binding. An installed Codex can use its existing local authentication; do not transmit credentials through this gateway. Unannotated protocol payloads remain visible in the in-memory journal. No token count or cost is invented from missing usage, message counts or Session writes. The HTTP adapter targets OpenAI Responses. Its [projected profile](https://github.com/rastok-io/rastok/blob/2e5128c76faf35cc879211138f429a4048608c77/docs/architecture/openai-responses-hydration.md) is qualified locally, including original samples from a held Retry attempt on an inert test endpoint. This does not authorize retrying model inference. `secret()` is bound only at the HttpClient Driver boundary; its bearer is not recorded or displayed. That boot-dependent profile still refuses diagnostic recording, rather than persisting deployment secrets or inventing replay inputs. Disconnecting a socket is not the same as canceling an agent turn. The idle lifetime bounds abandoned conversations but does not restore child memory after restart. Details and the exact test commands live in the [composition evidence](https://github.com/rastok-io/rastok/blob/2e5128c76faf35cc879211138f429a4048608c77/docs/architecture/agent-gateway-showcase.md). The service mock responds to inputs with frames and an optional terminal. Unsolicited/delayed scripted frames, system-close acknowledgements and `now()` in Session mocks remain named limits. The deployment journal is not durable. --- --- title: Instances, state and time description: Choose the owner of state, separate instance keys from lifetimes, and make closure and bounded waiting explicit. url: https://docs.rastok.com/guide/06-instances-state-and-time source_revision: v0.2.0-alpha --- # Instances, state and time After this chapter you can choose an instance key, distinguish immutable values from private mutable state, and explain when a lifetime or a bounded join produces work. The central question is ownership: which tenant or sensor does this arrival belong to, and which live instance may consume it? ## Select an instance In `examples/keyed-retry.rkg`, lines 19–21, the App declares three independent policies: ```rkg instance = { key = data.tenant } lifetime = { kind = idle; max = duration("10s") } closing = { drain_for = duration("1s"); settle_for = duration("1s") } ``` The key selects Alice's or Bob's instance before delivery. An unkeyed child is a singleton within its parent, not across tenants. An Operator owns state and mailboxes; a Connector owns exchanges. A nested Graph types its key from its declared input, even before a Connector that accepts `variant`. Keys do not create threads: the [Worker](/reference/execution.md) runs transactions sequentially while external Calls can remain open. Try a resident Process with `rastok run examples/agent-dialogue.rkg` and `cat` on PATH. Type a line and read its echo on `out`. The next line uses the same local session; Ctrl-C stops it. The key reads the entering envelope and permitted enclosing immutable values. Its type must be valid on every admitting input. Changing the payload (DATA) later does not move the current instance. When an address closes and later opens again, a new generation separates its clean state from old deliveries and deadlines. The journal records that exact destination generation. ## Values and mutable state A handler-local `val` lasts one transaction. A Node-level `val` can read that owner's `instance.key`, as can its handlers (including `on stop`) and instance-bound settings. A Graph can pass its key to children through a named `val`; the children never inherit `instance.key`. A `var` belongs to one Operator instance. In `examples/sensor-alarm.rkg`, lines 19–21, each sensor keeps its own alarm state, even across a silent period: ```rkg instance = { key = data.sensor } lifetime = { kind = persistent } var tripped: bool = false ``` Pump-a can be tripped while pump-b is normal. The state change and emission commit together in the owning Operator transaction. Another Operator cannot read that cell by name; shared mutable behavior needs an explicit Operator with typed inputs and outputs. See [`docs/spec/instances.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md) §§3–5. ## Choose a lifetime If you declare a key, you must also declare a lifetime. The key says which instance receives a delivery; the lifetime says when that instance closes. Without a key, omitting the lifetime still gives a persistent singleton. The attribute has the shape `lifetime = { kind = ... }`, with a positive `max` duration where required. | Kind | Meaning and additional field | |---|---| | `persistent` | No lifetime deadline | | `idle` | Close after admission silence, with `max = duration("10s")` | | `age` | Close at a fixed age from the creating admission, using `max` | | `once` | Admit one entering envelope into a generation, then request Closing | | `slot` | Select the epoch-aligned processing-time box at admission, with `max = duration("5m")` | Traffic refreshes an idle deadline, not an age deadline. An open Call alone is not admission activity. Slot boundaries are independent of boot time; the run's recorded start timestamp maps them onto the logical timeline. ## Close with explicit budgets Closing drains admitted work, then settles canceled Calls. Both durations are positive. Confirmed outcomes keep their typed exits; unconfirmed ones become `OutcomeUnknown` at the settlement deadline. A finite owner needs this policy when it is an outbound Connector or owns one in its subtree. The rule includes the root App. Children close before their parent, and later arrivals wait for a successor generation. Closure is neither a rollback nor permission to drop the old generation's outcomes. The full sequence is in [`docs/spec/instances.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md) §7.1. ## Bound a wait, then advance time `examples/sensor-alarm.rkg`, lines 34–44, correlates within the sensor instance: ```rkg operator watchdog { input probe: Sensor input heartbeat: Sensor output out: string output expired: MissedHeartbeat instance = { key = data.sensor } lifetime = { kind = persistent } on (probe, heartbeat) within duration("5m") { out = probe.data.sensor } } ``` `within` bounds how long each candidate waits; `last N` instead bounds the number retained per input. A bounded join must declare and wire `JoinExpired` on its `expired` output, even if the intended scenario always supplies both inputs. Deliberate `-> nothing` is a destination; silence is not. After a pair fires, the watchdog has no candidate or state to keep, but its sensor instance stays open for the next pair. Check reports this as [`W-EMPTY-INSTANCE`](/reference/diagnostics.md#instance-warnings). If the instance is finished instead, write `stop` on that branch. The Lab's `advance` visits due deadlines without sleeping. A partial join can be waiting while no work is runnable. `now()` observes the transaction's civil timestamp, derived from origin plus logical time; it does not trigger a handler. See [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) §§5, 7 and 8. ## Summary Keys select owners, `var` stores private state, and lifetimes determine when instances close. Joins bound retained candidates; the Lab advances their deadlines explicitly. Sliding/event-time windows and durable recovery are outside the [current alpha scope](/index.md#what-is-available-today). ## Next Continue with [Loops and retries](/guide/07-loops-and-retries.md), then compare [Two tenants](/examples/03-two-tenants.md) and [Sensor alarm](/examples/05-sensor-alarm.md). Explain which instance owns each pending Call or unmatched probe before running the scenario. --- --- title: WebSocketServer description: Ports, terminal outcomes, settings and qualification evidence for the WebSocketServer connector. url: https://docs.rastok.com/reference/connectors/websocket-server source_revision: v0.2.0-alpha --- # WebSocketServer `std/websocket-server@1`. Accepts peer Sessions. Replies follow session lineage or an explicit `correlate`. A pre-admission handshake refusal creates no Session or exit. ## Declaration This declaration comes from `examples/agent-gateway.rkg`. Place the Connector in a Graph and wire its ports; the excerpt alone is not an App. ```rkg connector clients : WebSocketServer { listen = "127.0.0.1:8443" path = "/agent" codec = json handshake_timeout = duration("5s") max_message = "1MiB" correlate = meta.ext.session_id versions = ["http/1.1"] } ``` The [contract index](/reference/contracts.md) explains shared settings, build features and the distinction between a Contract, a Lab model and an installed Driver. See [instance ownership and bounded admission](/reference/execution.md#instances-own-state-not-threads); this Contract uses Sessions, not the outbound Call queue rule. | Mode | Driver direction | Exchange | Lab model | Installed in this binary | |---|---|---|---|---| | No selector | inbound+outbound | session | `lab-websocket` | Not compiled | ## Ports and completion | Mode | Port | Direction | Type rule | |---|---|---|---| | all | `in` | input | `codec = bytes` → `array`; `codec = json` → `variant`; `codec = string` → `string` | | all | `out` | output | Same as `in` | | all | `exit` | output | WebSocketExit, below | | Mode | Output cardinality | |---|---| | all | Zero or more frames and writes; exactly one `exit` per Session | ## Exit union | Case | Payload | Call visibility | |---|---|---| | `Closed` | `{ code: int, reason: string }` | Not an outbound Call | | `ConnectFailed` | Empty | Not an outbound Call | | `DecodeFailed` | Empty | Not an outbound Call | | `DnsFailed` | Empty | Not an outbound Call | | `HandshakeRejected` | `{ status: int }` | Not an outbound Call | | `MessageTooLarge` | `{ limit: ulong }` | Not an outbound Call | | `OutcomeUnknown` | Empty | Not an outbound Call | | `ProtocolFailed` | Empty | Not an outbound Call | | `TimeoutExpired` | Empty | Not an outbound Call | | `TlsFailed` | Empty | Not an outbound Call | | `TransportLost` | Empty | Not an outbound Call | ## Settings With `codec = json`, `rastok check` refuses a producer whose resolved type contains a [value without a JSON form](/reference/types.md#json-request-values), using `E-TYPE-INVALID`. A `variant` producer is checked at execution instead: an unencodable message ends the Session with `DecodeFailed` before it is sent. | Mode | Setting | Domain | Presence / default | Latest phase | |---|---|---|---|---| | all | `allowed_origins` | `array` | optional | instance | | all | `auth_bearer` | `string` | optional | instance | | all | `behavior` | `deterministic` | `deterministic` | plan | | all | `codec` | `bytes \| json \| string` | required | plan | | all | `correlate` | `string` | optional | invocation | | all | `handshake_timeout` | `duration` | required | instance | | all | `headers` | `HTTP headers` | optional | instance | | all | `custom_headers` | `map>` | optional | instance | | all | `listen` | `string` | required | instance | | all | `max_message` | `ByteSize` | `"8MiB"` | plan | | all | `path` | `string` | `"/"` | plan | | all | `subprotocols` | `array` | optional | instance | | all | `tls_certificate` | `array` | optional | instance | | all | `tls_private_key` | `array` | optional | instance | | all | `versions` | `array` | `["http/3", "http/2", "http/1.1"]` | plan | | all | `zero_rtt` | `disabled` | `disabled` | plan | The Lab has an effectless Session binding, but authored WebSocket Session mocks are not executable. `rastok check` refuses a `mock` on this Connector with `E-CHECK-DEFERRED`; a declaration without a mock still checks. Driver tests cover Session opening, frames and terminal outcomes separately from a physical listener, authentication or wire handshake. Explicit correlation never chooses another Connector's Session. ## Qualification inventory No dedicated full-Contract fixture is declared. Related tests: `crates/rastok/src/connector/drivers/network/websocket.rs`. --- --- title: Diagnostics description: Compiler error codes, their trigger, the source change to make, and message excerpts from exercised refusals. url: https://docs.rastok.com/reference/diagnostics source_revision: v0.2.0-alpha --- # Diagnostics A graph that leaves a possible outcome with nowhere to go does not compile. `E-UNWIRED-OUTPUT` enforces that rule, including outputs that carry a fault. Codes starting with `W-`, including `W-JOIN-UNPAIRED`, are warnings, not refusals. Codes identify refusals; messages explain the particular source location. The code and structured fields are stable, while message wording can change. The examples below are excerpts collected from compiler runs on test inputs or from the internal-plan diagnostic regression. `check`, `simulate` and `run` all compile source first. A Parse or Check error therefore appears before simulation or physical I/O starts. The CLI prints a source span and, where relevant, the expected and found values. See [Command line](/guide/09-command-line.md) for exit status and invocation. ## Parse Lexing and parsing report malformed source, unavailable syntax and excessive decision nesting. | Code | When it fires | What the author changes | Example message excerpt | |---|---|---|---| | `E-DISPATCH-DEPTH` | Nested decisions exceed the Dispatch bound; also checked after parsing. | Split the decision into Operators instead of adding nesting. | “nested `match` decisions exceed the Dispatch depth budget” | | `E-JSON-VALUE` | A json! literal is not valid JSON. | Correct the JSON inside the literal. | “the JSON value does not read: unexpected `?`” | | `E-LEX-CHAR` | Character outside the source grammar. | Remove or quote the character. | “the character `-` is not part of the grammar” | | `E-LEX-UNTERMINATED-BLOCK` | Raw frontend block has unmatched delimiters. | Balance its braces and embedded strings. | “this raw block never closes” | | `E-LEX-UNTERMINATED-COMMENT` | Block comment reaches end of file. | Close the comment. | “this block comment never closes” | | `E-LEX-UNTERMINATED-STRING` | String reaches a line ending without its closing quote. | Close the string or use the appropriate multiline frontend. | “this string never closes before the end of the line” | | `E-PARSE-DEFERRED` | The parser recognizes a construct that this build does not implement. | Use the executable subset or omit that construct. | “an experiment syntax is not implemented by this build yet” | | `E-PARSE-EXPECTED` | A token cannot continue the current production. | Follow the expected token or statement shown at the source span. | “expected `{`, found `lab`” | ## Check Name resolution is included here because it happens before a plan exists. Its structured phase is `resolve`; the remaining rows have phase `check`. Independent plan validation can also surface these semantic refusals. ### Names and declarations | Code | When it fires | What the author changes | Example message excerpt | |---|---|---|---| | `E-APP-COUNT` | The compilation unit has zero or several App roots. | Keep exactly one graph annotated App. | “a deployed unit needs exactly one `: App` graph, found 0” | | `E-DUP-LAB-IDENTITY` | Simulation, scenario, mock or origin declarations conflict. | Remove the repeated declaration or distinguish its name. | “the scenario `same` is already declared at this level” | | `E-DUP-NODE` | Two children share a name in one Graph. | Give each child its own name. | “the node name `o` is already declared in this graph” | | `E-DUP-TYPE` | Two type declarations share a name. | Keep one definition for that name. | “the type `T` is already declared” | | `E-LAB-DUP` | More than one logical Lab name is declared. | Keep one Lab name; use simulation groups for different mock worlds. | “a unit has one logical Lab; use simulations for different mock worlds” | | `E-NAME-CLASH` | A child and a Graph port share a name. | Rename one declaration. | “`work` already names a Graph port; ports and children share one namespace” | | `E-NAME-RESERVED` | A declaration uses a reserved name, including a standard type or annotation. | Choose another name; use standard types without redeclaring them. | “`nothing` is a reserved word” | | `E-RESOLVE-UNKNOWN` | A referenced name has no declaration in scope. | Declare the name or correct its spelling. | “`ghost` names neither a Graph port nor a child Node in this Graph” | | `E-SIM-TARGET` | A simulation targets something other than the unit's App. | Omit the target or name the complete App boundary. | “a simulation closes the unit's App; sub-graph targets are a deferred capability” | ### Types, wiring and execution rules | Code | When it fires | What the author changes | Example message excerpt | |---|---|---|---| | `E-ASSET` | A build-time asset cannot be read within its root and size limits. | Correct the literal path, placement or asset size. | “this compilation has no asset root” | | `E-BRACE-MIXED` | A braced value mixes data members with envelope roots. | Place ordinary members inside data. | “this braced value mixes data fields with reserved envelope roots; wrap the data in `data = { … }`” | | `E-CHECK-DEFERRED` | A parsed construct has no executable lowering in this build. | Use a supported value or construct; also reported during Plan. | “a WebSocket Session mock is outside the executable subset of this build” | | `E-CONNECTOR-HANDLER` | A Connector contains a DSL handler. | Put application decisions in an Operator; the Driver implements the Contract. | “a Connector cannot own DSL handlers; its Contract and Driver events define its transitions” | | `E-CONNECTOR-STATE` | A Connector declares application-owned mutable state. | Keep that state in an Operator. | “a Connector's semantic state is defined by its Contract; author private `var` state in an Operator” | | `E-CONNECTOR-UNAVAILABLE` | The compiler has no executable definition for that Contract. | Choose a Contract and mode listed by rastok connectors. | “`Timer` is declared in the catalogue; its Driver is not in this build” | | `E-CONTENT-TYPE` | A content-type qualifier appears inside a nested value. | Apply it to the whole payload instead. | “a content type qualifies the WHOLE payload” | | `E-CONTRACT-ATTR` | A Connector attribute violates its mode's definition. | Use an allowed value and evaluation site from the Contract catalogue. | “`codec` violates the Process sheet: expected one of ["bytes", "jsonl", "lines"], got `utf16`” | | `E-CONTRACT-REQUIRED` | A required Connector setting is missing, or a Call mock's frames contradict its terminal. | Declare the setting, or match the response status: a 204 or 205 has no body. | “a 204 response has no body; remove `out` from this branch” | | `E-HANDLER-MISSING` | A route delivers to an Operator input that no handler consumes. | Route to an input handled by `on` or a join, or add its handler. A bare destination means `in`. | “`receiver.in` receives deliveries but `receiver` has no handler for `in`” | | `E-DATA-ANNOTATION` | A field annotation cannot be resolved or applied consistently. | Correct its name, constant arguments, target or measurement unit. | “unknown data annotation” | | `E-DISPATCH-POSITION` | A decision or guard occurs after work or in a conflicting position. | Place the decision first and combine duplicate guards. | “a handler admits at most one `where`; combine predicates or use one `match` dispatch” | | `E-DUP-BINDING` | A binding shadows a name already visible in its scope. | Rename the new binding. | “`limit` shadows an already visible binding” | | `E-DUP-KEY` | Two literal map keys canonicalize to the same value. | Keep a single entry for each canonical key. | “the map key `a` is already present” | | `E-EXPR` | An expression is invalid, unbound or outside the supported expression subset. | Correct the expression at the reported span. | “`mystery` is not a visible name” | | `E-EXTENSION-CONFLICT` | Extensions make incompatible demands on one owner. | Separate the owners, for example a Retry Connector inside a Loop Graph. | “Loop and Retry on the same owner are not admitted; put the Retry Connector inside a Loop Graph” | | `E-GRAPH-CYCLE` | Static wiring contains a cycle. | Keep wiring acyclic and express bounded recurrence with an Extension. | “the wiring cycles through `a`; edges form a DAG” | | `E-GRAPH-HANDLER` | A Graph contains application handler code. | Move the handler to an Operator child and wire it. | “a Graph cannot own application handlers; move the handler into an Operator child and wire its ports” | | `E-GRAPH-STATE` | A Graph declares private mutable state. | Move the state and transitions to an Operator. | “a Graph is a scope and cannot declare private `var` state; move the state and its handlers into an Operator child” | | `E-HANDLER-DUPLICATE` | An Operator repeats a handler for one trigger. | Combine its alternatives in one match. | “an Operator has exactly one handler for each trigger; put the alternatives in one `match`” | | `E-INSTANCE` | Instance keys, lifetime or closing settings do not satisfy their contract. | Correct the reported setting and supply bounded closing where required. | “closable owner `shell` contains outbound Connector `shell` and therefore requires `closing = { drain_for = ; settle_for = }`” | | `E-INSTANCE-COMMAND` | An instance closure command is used in an invalid routing position. | Use it only as a permitted final destination in its owning context. | “an instance closure command is a destination, never a source port or an intermediate endpoint” | | `E-LIFETIME-REQUIRED` | A Graph, Operator or Connector has a key but no authored lifetime. | Choose when its instances close, or write `lifetime = { kind = persistent }` to retain them. | “`decide` declares `instance.key` and no `lifetime`” | | `E-LOOP` | A Loop setting or finitude condition is invalid. | Supply a positive fuel bound or a provably decreasing measure. | “a `+ Loop` Executor requires positive `Loop.fuel` or a `Loop.measure` that can be proved finite” | | `E-LOOP-CARDINALITY` | Repeated frames could produce several verdicts for one application. | Derive the verdict from a once-per-application terminal. | “this Contract may produce several frames on the port; a Loop application needs exactly one verdict” | | `E-LOOP-CONTROL` | The checker cannot prove one verdict for every application path. | Follow the marked arm: declare its terminal output or select one verdict, not both. Call-hosted Loops also require finite timeouts. | “this arm of Loop `count` selects two verdicts: the terminal output `out` and `Loop.next`” | | `E-LOOP-ENTRY` | No unique recurrent input can be selected. | Declare the input and Loop.entry consistently. | “Loop needs one recurrent Graph input; declare `Loop.entry = `” | | `E-LOOP-HOST` | The host cannot provide a finite Loop application. | Use an Operator, admissible Graph or finite outbound Call. | “Loop requires an Operator or a resolved outbound Call Contract with closed frame and terminal guarantees” | | `E-LOOP-TERMINAL` | The selected terminal ports are ambiguous or incompatible. | Correct the host terminal declaration; Call terminals come from their Contract. | “every `Loop.terminal` item must name one output port” | | `E-MATCH-DUPLICATE` | One source has more than one closed route match. | Combine them into one route match. | “a source may have at most one closed route `match`” | | `E-MATCH-NONEXHAUSTIVE` | A possible case has no arm, or an ordered match lacks a fallback. | Cover the remaining cases or add the required fallback. | “an open match requires a final `_` fallback” | | `E-MATCH-NOT-CLOSED` | A closed match scrutinizes an open or unsupported type. | Match a closed union, enum or bool, or use ordered predicates. | “route `match` requires a pinned tagged union, enum, or bool source” | | `E-MATCH-OVERLAP` | Two closed match arms cover the same case. | Assign each case to one arm. | “route case `true` appears in two arms” | | `E-META-PREFIX` | One application metadata key is a prefix of another. | Choose keys that are consistently leaves. | “`meta.app.audit` is a leaf and `meta.app.audit.origin` makes it a branch” | | `E-META-SYS-READONLY` | A write targets metadata owned by execution. | Write application metadata under meta.app instead. | “meta.sys is read-only and runtime-owned; it is never an lvalue” | | `E-META-TYPE` | Writes to one application metadata field disagree on its type. | Use one type or separate fields. | “`meta.app.x` is written as int and as string: one field, one type” | | `E-META-ZONE` | The field is not in the zone's vocabulary, or an incoming route does not write the required application field. | Use a declared leaf. Write it on the named route, or use `meta.app.?field` to handle its absence. | “a metadata zone is not a value” | | `E-MULTI-EMIT-ARITY` | The output tuple and value tuple have different lengths. | Provide one value per output or use broadcast syntax. | “this atomic multi-emission has 3 targets but 2 tuple values” | | `E-MULTI-EMIT-DUPLICATE` | An atomic emission lists the same output twice. | Name each output once. | “output `left` appears twice in one atomic multi-emission” | | `E-NODE-ANNOTATION` | A Node's Contract and Extension annotation is invalid. | Declare the Contract and compatible Extensions in the required order. | “a Connector requires its exact Contract first, before every Extension” | | `E-PORT-CONFLICT` | A port is redeclared or inferred with incompatible roles. | Give the port one declaration and direction. | “`in` is already an input port of the graph; it cannot also be an output” | | `E-PORT-DIRECTION` | A port is used as a source, destination or emission against its direction. | Reverse the wiring or select the appropriate port. | “`chan` is an input port; an emission targets an output port” | | `E-PORT-TYPE` | A destination cannot accept the inferred value. | Match the named types and their differing fields, or narrow the value without an implicit lossy conversion. | “this route connects `Draft` to `Review`; pinned ends must agree: `Review` has no field `hash`, and `Draft` has no field `reviewer`” | | `E-PORT-UNKNOWN` | A Node has no port with the referenced name. | Use a declared port from that Node or Contract. | “`o` exposes no port named `mystery`” | | `E-RETRY` | A Retry setting is missing, repeated, misplaced or invalid. | Supply the required policy with positive bounds and valid settings. | “`Retry.attempts` must be a positive integer, first attempt included” | | `E-RETRY-CASES` | Retry.on does not select distinct declared terminal cases. | Use case names from the Contract's exit union, once each. | “`SpawnFailed` appears twice in Retry.on” | | `E-RETRY-EFFECT` | A selected retry case requires a repetition guarantee that is absent. | Select a before_effect case or declare a justified idempotence guarantee. | “Retry after `TimeoutExpired` (outcome_unknown) requires idempotent = true” | | `E-RETRY-HOST` | Retry is attached to something other than a supported outbound Call. | Put the policy on the outbound Call Connector. | “Retry requires an outbound Call Connector” | | `E-ROUTE-DUPLICATE` | Routing selects the same destination twice for one case. | Remove the duplicate route, including equivalent shorthand. | “destination `sink.in` is selected twice for the same source case” | | `E-ROUTE-MIXED` | One case is routed both to nothing and to a destination. | Choose discard or delivery for that case. | “`nothing` cannot coexist with a real destination for the same source case” | | `E-TYPE-BUDGET` | Type expansion exceeds a nesting, node, width or alias bound. | Reduce the dimension reported in the diagnostic. | “the type `Deep` nests 129 levels deep” | | `E-TYPE-DUP` | A field or symbol is repeated inside one type. | Remove or rename the duplicate member. | “the struct field `x` is declared twice” | | `E-TYPE-INVALID` | A type constructor violates its invariants, or a JSON input receives a known type without a JSON form. | Correct the type, or explicitly convert the named field before sending it. | “array<int> is not a canonical map-key type” | | `E-TYPE-RECURSIVE` | A named type expands back to itself. | Use a finite nonrecursive type. | “the type `Node` does not expand: `Node` reaches itself” | | `E-TYPE-UNRESOLVED` | An inference constraint reaches a position needing a closed type. | Supply a concrete type or enough contextual constraints. | “an open struct is an inference constraint, not an effective type” | | `E-UNION-OVERLAP` | Structural-union branches overlap in the values they accept. | Use disjoint branches or a tagged union. | “structural-union branches `int` and `long` overlap” | | `E-UNWIRED-OUTPUT` | A possible output or case has no explicit disposition. | Wire it to a destination or deliberately discard it with nothing. | “`o.side` can be produced but has no destination; route it or write `o.side -> nothing`” | | `E-WIRING-MIGRATION` | Wiring uses a removed spelling or continues after a command. | Use current port paths, match routing and final command destinations. | “edge `when` was removed; route a closed value with `-> match { ... }` or decide in an Operator” | ### Instance warnings | Code | When it fires | What the author changes | Example message excerpt | |---|---|---|---| | `W-EMPTY-INSTANCE` | A keyed `persistent` Operator can take a branch from its initial state that writes no state and does not stop. A join is checked when it fires. Without a deadline, the empty instance never closes on its own. | Give the instance a delay with `idle`, `age`, or `slot`. Use `stop` only if that branch ends its work. | “`dossier` can open an instance that retains nothing on `note`” | ### Lost-answer warnings | Code | When it fires | What the author changes | Example message excerpt | |---|---|---|---| | `W-MATCH-CATCHALL` | A wildcard on a finite outbound Call's terminal, or in the first handler receiving it, accepts a lost-answer case that no arm names. | Name each listed case, grouped or separately, even when its destination stays the same. | “the answer may have been lost while the operation succeeded” | The warning points to the written `_`. The `source` field names the terminal, `owner` names the Connector or receiving Operator, and `case` lists the unnamed cases. Check still succeeds. See [When the answer is lost](/guide/10-when-the-answer-is-lost.md). ### Join warnings | Code | When it fires | What the author changes | Example message excerpt | |---|---|---|---| | `W-JOIN-UNPAIRED` | A presence join receives frames and a terminal from one Call, but their counts do not pair for every terminal case. | Route every terminal accompanying a frame to the join, or key its Operator by the Call and bound the join with `within` or `last`. | “`ServerError` delivers 1 to `pair.body`, 0 to `pair.exit`; a lone delivery can pair with another Call” | The fields name the joining `node`, the source `connector`, its frame `port` and the terminal `case`. For a zero-or-more frame port, `case = "all"` means the warning is independent of one terminal case, not that every run fails. A bound without an instance key does not separate Calls. The warning does not change execution or make a failed scenario pass. ## Plan `E-PLAN-DEPTH` also occurs at Check when an expression exceeds its 128-level bound, measured on the resolved tree with compiler-added conversions included. Plan checks the combined serialized representation against the reader's separate 256-level bound, with the root at level zero. | Code | When it fires | What the author changes | Example message excerpt | |---|---|---|---| | `E-INTERNAL-PLAN` | Compiler output fails independent plan validation. | Report the source and diagnostic as a compiler defect. | “the lowering emitted an invalid plan” | | `E-PLAN-DEPTH` | The complete serialized plan exceeds the reader's bound; expressions also have a smaller Check bound. | Reduce combined nesting; the message identifies the boundary. | “the serialized plan reaches level 256; the format requires a level below 256 (root is level 0)” | The internal-plan case is a compiler defect, not an invitation to weaken a type or discard an outcome. Its message is exercised by `compiler::tests::the_internal_plan_diagnostic_carries_its_registered_payload`. ## Simulate The current runner reports failed scenarios, missing observations and golden differences as scenario results, not as additional structured `E-…` codes. For a golden mismatch it names the scenario, record, expected and obtained values, and cause. Correct the graph or the scenario; save a new trace only after reviewing the intended change. See [The Lab](/reference/lab.md#golden-traces) and [Echo](/examples/01-echo.md#read-the-golden-difference). A `TimeoutExpired`, `JoinExpired` or `LoopExpired` value is a typed outcome that the graph routes. It is not a compiler diagnostic. ## Run Deployment refusals, unavailable physical Drivers and recording/replay errors currently use contextual command errors, without a separate registry of emitted `E-…` codes. Use the reported Connector path, missing binding or format mismatch to correct the deployment or select the matching artifact. Command usage errors go to stderr with status 2; compilation and execution errors return a nonzero status. See [Command line](/guide/09-command-line.md). ## Specified, not shipped Source registry: [`docs/spec/diagnostics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/diagnostics.md), “Registry”. | Code | Status in this build | Specification | |---|---|---| | `E-SAGA-DURABILITY` | Saga durability checking is a deferred tool surface. | [`docs/spec/diagnostics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/diagnostics.md), Registry | | `E-COMPENSATE-KEY` | Compensation-key checking is deferred with Saga. | [`docs/spec/diagnostics.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/diagnostics.md), Registry | | `E-REPLAY-VERSION-MISMATCH` | Replay checks compatibility, but does not emit this structured code. | [`docs/spec/identity.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/identity.md) | | `E-LOOP-CONTEXT` | The name occurs in an execution refusal, not a structured compiler diagnostic. | [`docs/spec/loop.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/loop.md) | | `E-DUP-EDGE` | Superseded by `E-ROUTE-DUPLICATE`; the route check reports duplicate destinations. This code is not emitted. | [`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md) | --- --- title: "Countdown: a bounded loop" description: Prove that a countdown terminates, follow its manager commands, and see the checker reject a measure that cannot prove progress. url: https://docs.rastok.com/examples/07-countdown source_revision: v0.2.0-alpha --- # Countdown: a bounded loop This program counts down from an integer and emits one final message. A conversation keeps a resource alive until closure. A countdown asks the opposite question: can the program prove that repeated work will finish? The answer is written beside the Operator, without a backwards graph edge. The [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for the program and Lab, `.rkc` for a reviewed scenario reference and `.rkr` for a real execution recording. ## Run From the repository root, with `rastok` installed: ```sh rastok simulate examples/countdown.rkg --compare examples/traces/countdown ``` ```text PASS proof.positive PASS proof.already_finished 2 scenario(s), 0 failed ``` Add `--ui` to inspect each admitted application and its manager transition. ```sh rastok simulate examples/countdown.rkg --compare examples/traces/countdown --ui ``` This requires `hosted-ui`. Open the private loopback URL printed by the CLI. For the controls and source view, see [the debugger tour](/debugger.md). ## Read the program The App wires `in -> count -> out`. Inside `count`, a positive integer produces `Loop.next = data - 1`; otherwise the Operator emits `liftoff`. `Loop.next` is a command to the Loop manager, not a port or a graph edge. The manager records the command and admits the next application after the previous one has finished. `Loop.state` is the envelope admitted for the current application. `Loop.measure = Loop.state.data` selects its integer DATA as the decreasing quantity. The positivity guard and subtraction by one provide the proof. The terminal `out` supplies the final Done verdict. This example needs no exhaustion output because its measure proves termination. With an explicit fuel bound, possible exhaustion instead produces `LoopExpired { last_state: EntryType }` on the host's declared terminal, normally `err` for an Operator or `exit` for a Call. It must have a destination. Loop never adds a synthetic expiry port. See [`docs/spec/loop.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/loop.md) §§8 and 10. There is no Connector in this program. The [Lab reference](/reference/lab.md) explains expectations and observation windows; `advance` supplies virtual time. Source: `examples/countdown.rkg` ```rkg // A passive App wires one finite Operator application. The measure proves // termination; Loop.next is a manager command, not a spatial back-edge. graph countdown : App { input in: int output out: string operator count : Loop { input in: int output out: string Loop.measure = Loop.state.data on in match { data > 0 => Loop.next = data - 1 _ => out = "liftoff" } } in -> count -> out } lab proof { scenario positive { app.in = 3 expect app.out == "liftoff" } scenario already_finished { app.in = 0 expect app.out == "liftoff" } } ``` ## Expected result `proof.positive` admits states 3, 2, 1 and 0, then emits one `liftoff`. `proof.already_finished` admits 0 and emits the same result without recurrence. The CLI ends with `2 scenario(s), 0 failed`. Inspect the positive trace: ordinary Operator transactions produce commands; Manager transactions, labeled `l:loop` in the trace, record its progress. Four applications and three recurrences are different counts. Each application has its own causal identity even when it belongs to the same run. ## Break it Replace `Loop.measure = Loop.state.data` with `Loop.measure = 3`, then run: ```sh rastok check examples/countdown.rkg ``` The checker reports exactly: ```text error[E-LOOP]: this Loop cannot be proved finite: the Loop measure is outside the supported direct integer-path fragment --> examples/countdown.rkg:7:3 | 7 | operator count : Loop { | ^^^^^^^^^^^^^^^^^^^^^^^ = detail: this Loop cannot be proved finite: the Loop measure is outside the supported direct integer-path fragment ``` Restore the measure before trying the next edit (this discards edits to the example): ```sh git checkout -- examples/countdown.rkg ``` For a runtime comparison, change only the Operator's `out = "liftoff"` to `out = "changed"` and run the complete comparison below. ```sh rastok simulate examples/countdown.rkg --compare examples/traces/countdown ``` ```text FAIL proof.positive expect app.out == "liftoff" (countdown.rkg:24) observed app.out: "changed" expected 1 matching delivery on app.out, but observed 0 golden divergence: record 14: emissions(23)[0][2] . data(5)[1] (ccbor value)[1]; expected "liftoff"; got "changed"; cause: TRANSACTION "count" · trigger "p:in" · cause_id absent FAIL proof.already_finished expect app.out == "liftoff" (countdown.rkg:28) observed app.out: "changed" expected 1 matching delivery on app.out, but observed 0 golden divergence: record 5: emissions(23)[0][2] . data(5)[1] (ccbor value)[1]; expected "liftoff"; got "changed"; cause: TRANSACTION "count" · trigger "p:in" · cause_id absent 2 scenario(s), 2 failed ``` Restore the checked-in source (this discards your edits to this example): ```sh git checkout -- examples/countdown.rkg ``` ## Read the golden difference The invalid measure is rejected before execution, so it creates no new trace. The changed output, by contrast, changes an emission: the golden comparison names the first differing record, expected and actual values, and its cause. The unchanged scenario expectation also rejects the changed text. Restore the output rather than saving over the reference.
Inspect the raw sealed trace (.rkc) The versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence. Source: `examples/traces/countdown/proof.positive.rkc` ```rastok-trace a6070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582024382020309636c61620a000b000d81826c2e696e3e636f756e742e696e8249828165636f756e748000 a7070211601282438280800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8 a807021165636f756e74128249828165636f756e74800013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c81822824382808000 a807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a50f3df1105112054d397a04ed0666ca4c81828a105818701502fcfad2f040f633a2eaa6ac52c55d15c8249828165636f756e74800082025009426b9ccc12398e2552b10d29a250f762696e04a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820243820203 a807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a50f3df1105112054d397a04ed0666ca4c81828a105818503502fcfad2f040f633a2eaa6ac52c55d15c005009426b9ccc12398e2552b10d29a250f7a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820243820203 a707021165636f756e74128249828165636f756e7480001364703a696e1481836c2e696e3e636f756e742e696e8243828080000117801828a20181502fcfad2f040f633a2eaa6ac52c55d15c03818450bce978a7369910794ccef6fd5aaee307502fcfad2f040f633a2eaa6ac52c55d15c008201a501501acf1fd1704b6331132d400037b54c3a0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820243820202 a807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a501acf1fd1704b6331132d400037b54c3a1828a2048150bce978a7369910794ccef6fd5aaee30705818702502fcfad2f040f633a2eaa6ac52c55d15c00010350bce978a7369910794ccef6fd5aaee307a501501acf1fd1704b6331132d400037b54c3a0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c8040105820243820202 a907021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181981835020946af912fea1c531b9a8c156c5c0067829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e748000181a5020946af912fea1c531b9a8c156c5c0061828a105818503502fcfad2f040f633a2eaa6ac52c55d15c015020946af912fea1c531b9a8c156c5c006a5015020946af912fea1c531b9a8c156c5c00602501acf1fd1704b6331132d400037b54c3a0350f3df1105112054d397a04ed0666ca4c8040105820243820202 a707021165636f756e74128249828165636f756e7480001364703a696e1481837829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e7480000117801828a20181502fcfad2f040f633a2eaa6ac52c55d15c03818450dc759cce07b7cd08e3c541091909eac2502fcfad2f040f633a2eaa6ac52c55d15c018201a50150af90e571f28b0c57cc303bb4639eb522025020946af912fea1c531b9a8c156c5c0060350f3df1105112054d397a04ed0666ca4c8040105820243820201 a807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a50af90e571f28b0c57cc303bb4639eb5221828a2048150dc759cce07b7cd08e3c541091909eac205818702502fcfad2f040f633a2eaa6ac52c55d15c01020250dc759cce07b7cd08e3c541091909eac2a50150af90e571f28b0c57cc303bb4639eb522025020946af912fea1c531b9a8c156c5c0060350f3df1105112054d397a04ed0666ca4c8040105820243820201 a907021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181981835001149eb903f2a42a411bd2a5c99fda297829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e748000181a5001149eb903f2a42a411bd2a5c99fda291828a105818503502fcfad2f040f633a2eaa6ac52c55d15c025001149eb903f2a42a411bd2a5c99fda29a5015001149eb903f2a42a411bd2a5c99fda290250af90e571f28b0c57cc303bb4639eb5220350f3df1105112054d397a04ed0666ca4c8040105820243820201 a707021165636f756e74128249828165636f756e7480001364703a696e1481837829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e7480000217801828a20181502fcfad2f040f633a2eaa6ac52c55d15c0381845070adccffc97318389abff806c642078f502fcfad2f040f633a2eaa6ac52c55d15c028201a501506f63ca530a3ff07e0a2e0b98b1c07fdb025001149eb903f2a42a411bd2a5c99fda290350f3df1105112054d397a04ed0666ca4c8040105820243820200 a807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a506f63ca530a3ff07e0a2e0b98b1c07fdb1828a204815070adccffc97318389abff806c642078f05818702502fcfad2f040f633a2eaa6ac52c55d15c0203015070adccffc97318389abff806c642078fa501506f63ca530a3ff07e0a2e0b98b1c07fdb025001149eb903f2a42a411bd2a5c99fda290350f3df1105112054d397a04ed0666ca4c8040105820243820200 a907021165636f756e74128249828165636f756e74800013666c3a6c6f6f70148017801819818350a08ecae7e45001287125498fcbb858fa7829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e748000181a50a08ecae7e45001287125498fcbb858fa1828a105818503502fcfad2f040f633a2eaa6ac52c55d15c0350a08ecae7e45001287125498fcbb858faa50150a08ecae7e45001287125498fcbb858fa02506f63ca530a3ff07e0a2e0b98b1c07fdb0350f3df1105112054d397a04ed0666ca4c8040105820243820200 a707021165636f756e74128249828165636f756e7480001364703a696e1481837829406c6f6f703a32666366616432663034306636333361326561613661633532633535643135633a696e8249828165636f756e74800003178183636f757400a501507b1488260cb97cfd8331c5237d727d300250a08ecae7e45001287125498fcbb858fa0350f3df1105112054d397a04ed0666ca4c804010582024a8206676c6966746f66661828a20181502fcfad2f040f633a2eaa6ac52c55d15c0381845050b117f43155e440bad41482136d4336502fcfad2f040f633a2eaa6ac52c55d15c03820382507b1488260cb97cfd8331c5237d727d3001 a807021165636f756e74128249828165636f756e74800013666c3a6c6f6f7014801780181a507b1488260cb97cfd8331c5237d727d301828a204815050b117f43155e440bad41482136d433605818404502fcfad2f040f633a2eaa6ac52c55d15c0301 seal 104ac3b13f441a7ad2128e83fbff1abc3e3f4aeb9f9a4505d38e4a9dc2ecfbb1 ```
## Carry forward Previous: [Agent gateway](/examples/06-agent-gateway.md). Separate a resource's lifetime from a finite algorithm's progress. A Loop advances authored state; a Retry repeats a prepared operation. Next: [HTTP model adapter](/examples/08-model-adapter.md), which adds typed usage evidence to an external response. ## Limits This is a pure integer countdown, with no external program or elapsed-time claim. The direct proof fragment is deliberately small; unsupported proofs require a finite fuel bound and an explicit exhaustion disposition. The journal remains in memory; a golden trace is comparison evidence, not durable recovery. --- --- title: "Loops and retries: bounded recurrence" description: Separate authored state progression from safe repetition of one prepared Call, with explicit bounds, delays and terminal outcomes. url: https://docs.rastok.com/guide/07-loops-and-retries source_revision: v0.2.0-alpha --- # Loops and retries: bounded recurrence After this chapter you can choose Loop for state progression and Retry for repeating one operation, explain their bounds, and identify the guarantee needed before repeating a visible external effect. Both use a journal-owned manager. Neither introduces a backwards edge into the directed acyclic graph (DAG). ## Advance a state with Loop Read `examples/countdown.rkg`, lines 7–16: ```rkg operator count : Loop { input in: int output out: string Loop.measure = Loop.state.data on in match { data > 0 => Loop.next = data - 1 _ => out = "liftoff" } } ``` Each application either produces a new state through `Loop.next` or ends through its terminal output. The command is recorded in the producing transaction. The manager later consumes it and admits another application. It is a command destination, not an output port or an edge to wire backwards. `Loop.state` is the complete envelope admitted for the current application. Its DATA is an integer here. `Loop.measure` selects the quantity whose strict decrease proves termination: a direct integer path, a positivity guard and literal subtraction are within the executable proof fragment. Input 3 needs four applications, ending at 0. A constant measure is not a progress proof. `Loop.again` retains that admitted state; `Loop.done` finishes without a business output. Every application needs exactly one verdict. A terminal output such as `out` supplies Done implicitly; `nothing` only disposes an output and does not itself finish a Loop application. ## Bound and delay the applications At least one of `Loop.measure` or `Loop.fuel` is required. Positive `Loop.fuel = N` permits at most N applications, including the first. If the last application requests another, the manager emits `LoopExpired { last_state: EntryType }` on the existing host terminal. An Operator normally declares `err` for that case; a Call uses `exit`. The terminal must be typed and wired like every other productible outcome. The measure-only countdown proves exhaustion impossible, so it needs no expiry declaration. `Loop.delay = { kind = fixed; after = duration("1s") }` sets a fixed delay. A delay may also be exponential, with `kind = exponential`, `first` and `ceiling`. Durations are positive; there is no jitter. The delay starts when the manager consumes the command after the application has no outstanding work. No next application overlaps the previous one. See [`docs/spec/loop.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/loop.md) §§7–10. ## Repeat an operation with Retry The webhook uses `examples/webhook-to-partner.rkg`, lines 91–95: ```rkg idempotent = true behavior = deterministic Retry.attempts = 2 Retry.on = [ServerError, TimeoutExpired, DnsFailed, ConnectFailed] Retry.delay = { kind = fixed; after = duration("1s") } ``` The manager retains one prepared request, including evaluated settings and the partner key. Attempts reuse it; invocation expressions are not evaluated again. `Retry.attempts` includes the first Call. `Retry.on` is a static set of terminal case names, not a predicate over arbitrary response DATA. Fixed delay uses `after`. Exponential delay uses `first` and `ceiling`, with `first <= ceiling`; after failed attempt i its delay is `min(first * 2^(i - 1), ceiling)`. It starts at the winning Call closure, not when a delayed manager happens to run. Each attempt remains in the journal; only the final batch, its response frames and terminal outcome, is delivered downstream. Exhaustion forwards the last terminal unchanged, without a new Retry error case. ## Check repetition safety separately The Contract classifies every terminal: | Class | Meaning for repetition | |---|---| | `before_effect` | The operation has not become externally visible; Retry may select it without an idempotence guarantee | | `outcome_unknown` | Visibility or outcome is uncertain; Retry requires `idempotent = true` | | `after_effect` | The operation became visible; Retry requires `idempotent = true` | The checker enforces that rule for every selected case. A decoded HTTP 500 is `ServerError`, an `after_effect` response, not a transport fault. The webhook's real partner must honor the declared same-request guarantee; merely sending an idempotency key does not establish it. `behavior = deterministic | probabilistic` describes results, not repetition safety. A deterministic payment can still charge twice. An inference may return different text and incur another charge, which is why the model adapter omits Retry. Loop proves finitude, not effect safety; its advisory `W-LOOP-REPEAT` is distinct from Retry's hard refusal. ## Summary Loop chooses the next state; Retry keeps the same prepared operation. Their bounds and delays are explicit. A Loop Graph may contain Retry Calls; the enclosing application waits for them through backoff and final closure. Compensation belongs to the future Saga contract, not a global `effect` attribute. See [`docs/spec/retry.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/retry.md), [`docs/spec/effects-and-sagas.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/effects-and-sagas.md) and the [current alpha scope](/index.md#what-is-available-today). ## Next If a partner may have acted before its response disappeared, read [When the answer is lost](/guide/10-when-the-answer-is-lost.md). Continue with [Privacy, secrets and measurements](/guide/08-privacy-secrets-and-measurements.md). Practice the distinction in [Countdown](/examples/07-countdown.md) and [Webhook to partner](/examples/04-webhook-to-partner.md): identify the verdict or terminal that permits each recurrence before advancing time. --- --- title: Standard library description: Find the types, Connector Contracts, annotations and value frontends supplied with Rastok. url: https://docs.rastok.com/reference/stdlib source_revision: v0.2.0-alpha --- # Standard library The standard library supplies definitions that an application can use without copying them into its source. A Connector Contract describes an interaction; a Driver implements it. Selecting physical Drivers does not change the standard types available to the compiler. ## Types These names are available without an import or a local declaration. Their definitions are the same logical types used by the Connector ports. | Type | Definition and cases | |---|---| | `FileExit` | [File](/reference/connectors/file.md#exit-union), read and replace | | `ProcessExit` | [Process](/reference/connectors/process.md#exit-union), job and service | | `HttpClientExit` | [HttpClient](/reference/connectors/http-client.md#exit-union) | | `HttpServerExit` | [HttpServer](/reference/connectors/http-server.md#exit-union), ack and respond | | `WebSocketExit` | [WebSocketClient](/reference/connectors/websocket-client.md#exit-union) and [WebSocketServer](/reference/connectors/websocket-server.md#exit-union) | Write `output failed: FileExit` without a `type FileExit` declaration. These names also work in aliases, fields, collections and `is`/`as`. For example, `type StorageResult = FileExit` declares an application alias without creating a different type identity. Redeclaring a standard name is `E-NAME-RESERVED`. A typed destination resolves constructors such as `Completed {}`; without one, constructor lookup uses only unions explicitly declared in the source. The [type reference](/reference/types.md) covers scalar, collection, struct and union notation and schema projections. ## Connector Contracts [Connectors and contracts](/reference/contracts.md) lists File, Process, HttpClient, HttpServer, WebSocketClient and WebSocketServer. Each Connector page gives its exact Contract id, modes, ports, settings, terminal outcomes and qualification limits. `rastok connectors` lists the Contracts and the implementations present in the current binary; `rastok connectors --json` produces the machine-readable catalog. Physical networking depends on the binary's feature selection, not on an import in the program. ## Annotations | Annotation | Meaning | |---|---| | `@sensitive(level = ...)` | Classifies confidentiality as `Internal`, `Confidential` or `Restricted` | | `@personal(...)` | Classifies personal data with identifier, special and criminal flags | | `@secret` | Declares secret handling; clear secret-bearing executable schemas are refused | | `@measure(id = ..., unit = ...)` | Associates a numeric field with a measurement id and unit | These annotations are available without imports. Their interpretation and current limits are described in [Privacy, secrets and measurements](/guide/08-privacy-secrets-and-measurements.md). A user annotation with the same field shape does not acquire the authority of a standard annotation. ## Value frontends and expressions The standard tagged frontends are `json!` for a JSON value, `string!` for verbatim text and `base64!` for bytes. Their syntax and restrictions are in [Expressions and dispatch](/reference/expressions.md#tagged-frontends). That reference also lists the available operators and expression functions. ## Modules and imports There is no `import`, `use` or `using` directive in this version. Standard definitions are available implicitly. Modules, explicit imports, visibility and namespace rules remain a later design discussion; no syntax or delivery date is decided. ## Specified, not shipped | Item | Specification | |---|---| | File `watch`, Timer, Calendar and Memory | [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §§3.4–3.7; see the [Contract limits](/reference/contracts.md#specified-not-shipped) | | Additional tagged guest-language frontends | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §§2–3; see the [expression limits](/reference/expressions.md#specified-not-shipped) | Sources: [`docs/spec/stdlib.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/stdlib.md) §1.2, [`docs/spec/types.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/types.md), [`docs/spec/annotations.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/annotations.md) and the standard Contract definitions. --- --- title: "HTTP model adapter: typed responses and token metering" description: Select a typed view of an OpenAI Responses result, retain original token measurements by job and session, and distinguish absent usage from an observed zero. url: https://docs.rastok.com/examples/08-model-adapter source_revision: v0.2.0-alpha --- # HTTP model adapter: typed responses and token metering This program sends a model request and keeps the response's reported usage with its job and session. A bounded loop tells you how much work may repeat. At a model boundary, another question matters: what usage did the partner actually report? Keep that evidence on the original typed response, without turning an absent field into a zero or counting a downstream copy again. The [file formats](/guide/09-command-line.md#file-formats) are `.rkg` for the program and Lab, `.rkc` for a reviewed scenario reference and `.rkr` for a real execution recording. ## Run From the repository root, use the synthetic fixture bindings and the checked [deployment profile](https://github.com/rastok-io/rastok/blob/2e5128c76faf35cc879211138f429a4048608c77/examples/agent-http.deployment.json): ```sh RASTOK_SHOWCASE_MODEL_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_MODEL_TOKEN_VERSION=fixture-v1 rastok simulate examples/agent-http.rkg --deployment examples/agent-http.deployment.json --compare examples/traces/agent-http ``` ```text PASS responses.two_sessions PASS responses.missing_usage PASS responses.observed_zero PASS responses.schema_failure PASS responses.transport_failure PASS responses.http_errors 6 scenario(s), 0 failed ``` Add `--ui` for the paused debugger. ```sh RASTOK_SHOWCASE_MODEL_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_MODEL_TOKEN_VERSION=fixture-v1 rastok simulate examples/agent-http.rkg --deployment examples/agent-http.deployment.json --compare examples/traces/agent-http --ui ``` This requires `hosted-ui`. Open the private loopback URL printed by the CLI. The Lab never contacts the profile's configured model URL. These fixture values are not credentials. For the controls and source view, see [the debugger tour](/debugger.md). ## Read the program Start with `ResponseUsage` and `ModelResponse`. The former marks the three original quantities with `@measure(id = ..., unit = "token")`. The latter is an explicit selected view of an external JSON object: response identity, output, status, usage and error. The `model` [HttpClient](/reference/connectors/http-client.md) refines its existing port with `output out: ModelResponse`. Under `codec = json` and `json_profile = projected`, deserialization keeps declared members, omits additional members and turns an absent nullable member into null. A member with the wrong type produces `DecodeFailed`; its `message` names the field and the expected type without copying the received value. Ordinary structs and strict JSON deserialization remain closed. `request` carries `session` and `job` into META. `explain_usage` emits an explanation when usage is absent; it neither extracts nor sums measurements. `terminal` separates a usable 2xx response from other HTTP outcomes. One job means one non-streaming inference, not a resident conversation. The bearer is a logical `secret("showcase/model/token")` reference. Its value is bound at boot and supplied only at the real HttpClient Driver boundary. `behavior = probabilistic` describes the partner's outputs. It does not mean that repeating a request is safe: there is no Retry on this inference. The [Lab reference](/reference/lab.md) explains mock responses, expectations and observation windows. `advance` supplies virtual time; a mock's terminal response ends its simulated exchange, not the whole scenario. Source: `examples/agent-http.rkg` ```rkg // Each job makes one HTTP request and reports the usage in the model's reply. // The Lab scripts replies; the graph never retries a potentially billable request. val model_name = "gpt-6-astra" val simulated_message = json! {"type":"message","role":"assistant","content":[{"type":"output_text","text":"Hello from the simulated model.","annotations":[]}]} type Job = struct { session: string, job: string, prompt: string } type JsonObject = map type ResponseUsage = struct { input_tokens: ulong @measure(id = input_tokens, unit = "token") output_tokens: ulong @measure(id = output_tokens, unit = "token") total_tokens: ulong @measure(id = total_tokens, unit = "token") input_tokens_details: JsonObject? output_tokens_details: JsonObject? } type ModelResponse = struct { id: string object: string output: array status: string? usage: ResponseUsage? error: JsonObject? } type UnknownUsage = struct { session: string, job: string, reason: string } graph agent_http : App { input in: Job output response: ModelResponse output unknown: UnknownUsage output failed: HttpClientExit instance = { key = data.session } lifetime = { kind = idle; max = duration("2h") } closing = { drain_for = duration("30s"); settle_for = duration("5s") } operator request { input in: Job output out: variant on in { val body = { model = model_name; input = data.prompt; stream = false; store = false; max_output_tokens = 128 } out = { data = body as variant meta.app.session = data.session meta.app.job = data.job } } } connector model : HttpClient { url = env("MODEL_URL") auth_bearer = secret("showcase/model/token") method = "POST" codec = json json_profile = projected output out: ModelResponse timeout = duration("10s") max_body = "256 KiB" behavior = probabilistic } // Quantities already live on model.out. This Operator only explains absence; // it neither extracts, copies nor totals measurements. operator explain_usage { input in: ModelResponse output unknown: UnknownUsage on in match { data.usage is ResponseUsage => nothing _ => unknown = { session = meta.app.session as string; job = meta.app.job as string; reason = "usage not reported" } } } operator terminal { input in: HttpClientExit output failed: HttpClientExit output unknown: UnknownUsage on in match { data is Completed => match { data.status >= 200 && data.status < 300 => nothing _ => failed = Completed { status = data.status } } data is ServerError => failed = ServerError { status = data.status } _ => { failed = . unknown = { session = meta.app.session as string; job = meta.app.job as string; reason = "no usable response" } } } } in -> request -> model model.out -> { response; explain_usage } explain_usage.unknown -> unknown // Lost answers go to the same handler, which reports the unknown usage. model.exit -> match { BodyTooLarge | DecodeFailed | OutcomeUnknown | ProtocolFailed | TimeoutExpired -> terminal Completed | ConnectFailed | DnsFailed | ServerError | TlsFailed -> terminal } terminal.failed -> failed terminal.unknown -> unknown } lab responses { // Mocks supply already typed values. Wire-shape refusals are separately // tested against the real HTTP decoder, not inferred from this Lab. mock model { on in match { meta.app.job == "missing" || meta.app.job == "null" => { out = { id = "resp_without_usage"; object = "response"; output = []; status = "completed"; usage = null; error = null } exit = Completed { status = 200 } } meta.app.job == "invalid" => exit = DecodeFailed { message = "response `out.usage.total_tokens` expects ulong; received string" } meta.app.job == "error_body" => exit = DecodeFailed { message = "response `out.id` expects string; required member is missing" } meta.app.job == "zero" => { out = { id = "resp_zero"; object = "response"; output = []; status = "completed"; usage = { input_tokens = 0u; output_tokens = 0u; total_tokens = 0u; input_tokens_details = null; output_tokens_details = null }; error = null } exit = Completed { status = 200 } } meta.app.job == "timeout" => nothing meta.app.job == "server_error" => { out = { id = "resp_failed"; object = "response"; output = []; status = "failed"; usage = null; error = {"message": "scripted service error"} } exit = ServerError { status = 500 } } _ => { out = { id = "resp_fixture" object = "response" output = [simulated_message] status = "completed" usage = { input_tokens = 12u; output_tokens = 4u; total_tokens = 16u; input_tokens_details = {"cached_tokens": 0}; output_tokens_details = {"reasoning_tokens": 0} } error = null } exit = Completed { status = 200 } } } } scenario two_sessions { app.in = { session = "alice"; job = "a1"; prompt = "Hello" } expect model.out where meta.app.session == "alice" && meta.app.job == "a1" app.in = { session = "bob"; job = "b1"; prompt = "Hello" } expect model.out where meta.app.session == "bob" && meta.app.job == "b1" app.in = { session = "alice"; job = "a2"; prompt = "Another independent job" } expect model.out where meta.app.session == "alice" && meta.app.job == "a2" expect app.unknown == nothing expect app.failed == nothing } scenario missing_usage { app.in = { session = "alice"; job = "missing"; prompt = "Hello" } expect app.unknown where data.reason == "usage not reported" app.in = { session = "alice"; job = "null"; prompt = "Hello" } expect app.unknown where data.reason == "usage not reported" expect app.failed == nothing } scenario observed_zero { app.in = { session = "alice"; job = "zero"; prompt = "Hello" } expect model.out where data.usage is ResponseUsage && data.usage.input_tokens == 0u && data.usage.output_tokens == 0u && data.usage.total_tokens == 0u expect app.unknown == nothing } scenario schema_failure { app.in = { session = "bob"; job = "invalid"; prompt = "Hello" } expect app.failed where data is DecodeFailed && data.message.contains("out.usage.total_tokens") expect app.unknown expect model.out == nothing } scenario transport_failure { app.in = { session = "alice"; job = "timeout"; prompt = "Hello" } advance duration("10s") expect app.failed == TimeoutExpired {} expect app.unknown expect model.out == nothing } scenario http_errors { app.in = { session = "alice"; job = "server_error"; prompt = "Hello" } expect app.failed where data is ServerError && data.status == 500 expect model.out app.in = { session = "alice"; job = "error_body"; prompt = "Hello" } expect app.failed where data is DecodeFailed && data.message.contains("out.id") expect model.out == nothing } } ``` ## Expected result The CLI ends with `6 scenario(s), 0 failed`: | Scenario | Evidence | |---|---| | `two_sessions` | Alice's two jobs and Bob's job retain their own session and original response; each fixture reports 12 input, 4 output and 16 total tokens | | `missing_usage` | Absent/null usage produces an explanation and no measurement sample | | `observed_zero` | Three explicitly reported zero quantities remain observations | | `schema_failure` | `DecodeFailed` supplies no partially usable `model.out` | | `transport_failure` | A ten-second logical timeout produces no usage and no repeated inference | | `http_errors` | A decoded 500 is `ServerError`; an incompatible error body is `DecodeFailed` | The three token quantities are separate facts, not three numbers to add together. Input plus output already accounts for the reported total in this fixture; the graph invents neither a monetary amount nor a missing quantity. ## Break it In the `simulated_message` constant, change `Hello from the simulated model.` to `A different model answer.`. Keep the expected trace unchanged and run the comparison below. The counts still match, but `responses.two_sessions` fails its golden comparison. The other five scenarios still pass. ```sh RASTOK_SHOWCASE_MODEL_TOKEN=lab-only-not-a-credential RASTOK_SHOWCASE_MODEL_TOKEN_VERSION=fixture-v1 rastok simulate examples/agent-http.rkg --deployment examples/agent-http.deployment.json --compare examples/traces/agent-http ``` ```text FAIL responses.two_sessions golden divergence: record 6: closure(32)[1][0][1][1]; expected 820f868265657272…(399 bytes); got 820f868265657272…(393 bytes); cause: EGRESS "model" · emitting_id 7c6e92c8de6b86d2…(16 bytes) · call_key absent PASS responses.missing_usage PASS responses.observed_zero PASS responses.schema_failure PASS responses.transport_failure PASS responses.http_errors 6 scenario(s), 1 failed ``` Restore the checked-in source (this discards your edits to this example): ```sh git checkout -- examples/agent-http.rkg ``` ## Read the golden difference The measured first divergence is `record 6: closure(32)[1][0][1][1]`: the expected encoded value has 399 bytes and the changed one 393 bytes. The cause is `EGRESS "model"`, with no Call key. The differing external response is recorded before downstream interpretation, even though the scenario's count assertions still hold. Restore the text; do not save over the reference to hide the changed answer.
Inspect the raw sealed trace (.rkc) The versioned reference stores one hex-encoded causal record per line, with an optional final seal line. Use the chapter's comparison commands to explain a divergence. Source: `examples/traces/agent-http/responses.two_sessions.rkc` ```rastok-trace a6070108a40150f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c80401058202582e820f8382636a6f628206626131826670726f6d707482066548656c6c6f826773657373696f6e820665616c69636509636c61620a000b000d81826e2e696e3e726571756573742e696e82581882816772657175657374818380018207820665616c69636500 a7070211601282508280818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8 a807021167726571756573741282581882816772657175657374818380018207820665616c6963650013676c3a737461727414801780181a50f3df1105112054d397a04ed0666ca4c8182282508280818380018207820665616c69636500 a807021167726571756573741282581882816772657175657374818380018207820665616c696365001364703a696e1481836e2e696e3e726571756573742e696e82508280818380018207820665616c6963650001178183636f757400a601507c6e92c8de6b86d2cd0b2595345189fe0250f3df1105112054d397a04ed0666ca4c80350f3df1105112054d397a04ed0666ca4c804010582025853820f858265696e70757482066548656c6c6f82716d61785f6f75747075745f746f6b656e738202188082656d6f64656c82066b6770742d362d6173747261826573746f72658201f4826673747265616d8201f406828363617070636a6f62820662613183636170706773657373696f6e820665616c6963651818818201506cef1737ef75613f4e28c116cf87754518198183507c6e92c8de6b86d2cd0b2595345189fe74726571756573742e6f75743e6d6f64656c2e696e82568281656d6f64656c818380018207820665616c69636500 a8070211656d6f64656c1282568281656d6f64656c818380018207820665616c6963650013676c3a737461727414801780181a507c6e92c8de6b86d2cd0b2595345189fe182282508280818380018207820665616c69636500 a60703181b507c6e92c8de6b86d2cd0b2595345189fe181c656d6f64656c181e5820abe16a58280893d680b03b5f8e959dec87401453a0760738fa73661b0463c913181f01182174726571756573742e6f75743e6d6f64656c2e696e a70703181b507c6e92c8de6b86d2cd0b2595345189fe181c656d6f64656c181e5820abe16a58280893d680b03b5f8e959dec87401453a0760738fa73661b0463c913181f02182082018282636f7574820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e738214108264657869748202581c82138269436f6d706c65746564820f818266737461747573820218c8182174726571756573742e6f75743e6d6f64656c2e696e a7070211656d6f64656c1282568281656d6f64656c818380018207820665616c696365001364703a696e14818374726571756573742e6f75743e6d6f64656c2e696e82581882816772657175657374818380018207820665616c6963650001178283636f757400a60150b50ee3bb021a25a906a15643703a0aaa02507c6e92c8de6b86d2cd0b2595345189fe0350f3df1105112054d397a04ed0666ca4c8040105820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e7382141006828363617070636a6f62820662613183636170706773657373696f6e820665616c69636583646578697400a601505c6a50d6bb594d1d03157c3a3519cb5c02507c6e92c8de6b86d2cd0b2595345189fe0350f3df1105112054d397a04ed0666ca4c80401058202581c82138269436f6d706c65746564820f818266737461747573820218c806828363617070636a6f62820662613183636170706773657373696f6e820665616c69636518198283505c6a50d6bb594d1d03157c3a3519cb5c766d6f64656c2e657869743e7465726d696e616c2e696e8258198281687465726d696e616c818380018207820665616c696365008350b50ee3bb021a25a906a15643703a0aaa781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82581e82816d6578706c61696e5f7573616765818380018207820665616c69636500 a80702116d6578706c61696e5f75736167651282581e82816d6578706c61696e5f7573616765818380018207820665616c6963650013676c3a737461727414801780181a50b50ee3bb021a25a906a15643703a0aaa182282508280818380018207820665616c69636500 a8070211687465726d696e616c128258198281687465726d696e616c818380018207820665616c6963650013676c3a737461727414801780181a505c6a50d6bb594d1d03157c3a3519cb5c182282508280818380018207820665616c69636500 a60702116d6578706c61696e5f75736167651282581e82816d6578706c61696e5f7573616765818380018207820665616c696365001364703a696e148183781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82568281656d6f64656c818380018207820665616c69636500011780 a6070211687465726d696e616c128258198281687465726d696e616c818380018207820665616c696365001364703a696e148183766d6f64656c2e657869743e7465726d696e616c2e696e82568281656d6f64656c818380018207820665616c69636500011780 a6070108a40150e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd0401058202582c820f8382636a6f628206626231826670726f6d707482066548656c6c6f826773657373696f6e820663626f6209636c61620a010b000d81826e2e696e3e726571756573742e696e825682816772657175657374818380018207820663626f6200 a70702116012824e8280818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd a8070211677265717565737412825682816772657175657374818380018207820663626f620013676c3a737461727414801780181a50e6c20d6146234b74a33da1c709e86efd1822824e8280818380018207820663626f6200 a8070211677265717565737412825682816772657175657374818380018207820663626f62001364703a696e1481836e2e696e3e726571756573742e696e824e8280818380018207820663626f620001178183636f757400a60150b312f77e5679f2bf2cf6a90512486e150250e6c20d6146234b74a33da1c709e86efd0350e6c20d6146234b74a33da1c709e86efd04010582025853820f858265696e70757482066548656c6c6f82716d61785f6f75747075745f746f6b656e738202188082656d6f64656c82066b6770742d362d6173747261826573746f72658201f4826673747265616d8201f406828363617070636a6f62820662623183636170706773657373696f6e820663626f62181881820150fd9b99717f323d91d5cf80e3988108a61819818350b312f77e5679f2bf2cf6a90512486e1574726571756573742e6f75743e6d6f64656c2e696e82548281656d6f64656c818380018207820663626f6200 a8070211656d6f64656c1282548281656d6f64656c818380018207820663626f620013676c3a737461727414801780181a50b312f77e5679f2bf2cf6a90512486e151822824e8280818380018207820663626f6200 a60703181b50b312f77e5679f2bf2cf6a90512486e15181c656d6f64656c181e5820abe16a58280893d680b03b5f8e959dec87401453a0760738fa73661b0463c913181f01182174726571756573742e6f75743e6d6f64656c2e696e a70703181b50b312f77e5679f2bf2cf6a90512486e15181c656d6f64656c181e5820abe16a58280893d680b03b5f8e959dec87401453a0760738fa73661b0463c913181f02182082018282636f7574820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e738214108264657869748202581c82138269436f6d706c65746564820f818266737461747573820218c8182174726571756573742e6f75743e6d6f64656c2e696e a7070211656d6f64656c1282548281656d6f64656c818380018207820663626f62001364703a696e14818374726571756573742e6f75743e6d6f64656c2e696e825682816772657175657374818380018207820663626f620001178283636f757400a601505ba912d3696d95a061b788ba2c4cacd70250b312f77e5679f2bf2cf6a90512486e150350e6c20d6146234b74a33da1c709e86efd040105820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e7382141006828363617070636a6f62820662623183636170706773657373696f6e820663626f6283646578697400a601504bca3916c10fb79f16e79de566b7c1550250b312f77e5679f2bf2cf6a90512486e150350e6c20d6146234b74a33da1c709e86efd0401058202581c82138269436f6d706c65746564820f818266737461747573820218c806828363617070636a6f62820662623183636170706773657373696f6e820663626f6218198283504bca3916c10fb79f16e79de566b7c155766d6f64656c2e657869743e7465726d696e616c2e696e82578281687465726d696e616c818380018207820663626f620083505ba912d3696d95a061b788ba2c4cacd7781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82581c82816d6578706c61696e5f7573616765818380018207820663626f6200 a80702116d6578706c61696e5f75736167651282581c82816d6578706c61696e5f7573616765818380018207820663626f620013676c3a737461727414801780181a505ba912d3696d95a061b788ba2c4cacd71822824e8280818380018207820663626f6200 a8070211687465726d696e616c1282578281687465726d696e616c818380018207820663626f620013676c3a737461727414801780181a504bca3916c10fb79f16e79de566b7c1551822824e8280818380018207820663626f6200 a60702116d6578706c61696e5f75736167651282581c82816d6578706c61696e5f7573616765818380018207820663626f62001364703a696e148183781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82548281656d6f64656c818380018207820663626f6200011780 a6070211687465726d696e616c1282578281687465726d696e616c818380018207820663626f62001364703a696e148183766d6f64656c2e657869743e7465726d696e616c2e696e82548281656d6f64656c818380018207820663626f6200011780 a6070108a401506c793d2fff3f39818152c34ffedee98103506c793d2fff3f39818152c34ffedee98104010582025840820f8382636a6f628206626132826670726f6d7074820677416e6f7468657220696e646570656e64656e74206a6f62826773657373696f6e820665616c69636509636c61620a020b000d81826e2e696e3e726571756573742e696e82581882816772657175657374818380018207820665616c69636500 a807021167726571756573741282581882816772657175657374818380018207820665616c696365001364703a696e1481836e2e696e3e726571756573742e696e82508280818380018207820665616c6963650002178183636f757400a60150d86e9f1831c6494789aa711badd7ddd302506c793d2fff3f39818152c34ffedee98103506c793d2fff3f39818152c34ffedee98104010582025865820f858265696e707574820677416e6f7468657220696e646570656e64656e74206a6f6282716d61785f6f75747075745f746f6b656e738202188082656d6f64656c82066b6770742d362d6173747261826573746f72658201f4826673747265616d8201f406828363617070636a6f62820662613283636170706773657373696f6e820665616c6963651818818201505d480b4d1cb0c47547a7f416398d9e481819818350d86e9f1831c6494789aa711badd7ddd374726571756573742e6f75743e6d6f64656c2e696e82568281656d6f64656c818380018207820665616c69636500 a60703181b50d86e9f1831c6494789aa711badd7ddd3181c656d6f64656c181e5820d58e69e99055a2805c230647ed967fef93b58b8b820b06ee81c958388772c531181f01182174726571756573742e6f75743e6d6f64656c2e696e a70703181b50d86e9f1831c6494789aa711badd7ddd3181c656d6f64656c181e5820d58e69e99055a2805c230647ed967fef93b58b8b820b06ee81c958388772c531181f02182082018282636f7574820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e738214108264657869748202581c82138269436f6d706c65746564820f818266737461747573820218c8182174726571756573742e6f75743e6d6f64656c2e696e a7070211656d6f64656c1282568281656d6f64656c818380018207820665616c696365001364703a696e14818374726571756573742e6f75743e6d6f64656c2e696e82581882816772657175657374818380018207820665616c6963650002178283636f757400a6015093f83c16cbcdd7c379cf6f05bcea521e0250d86e9f1831c6494789aa711badd7ddd303506c793d2fff3f39818152c34ffedee981040105820259018f820f8682656572726f72821382008207f68262696482066c726573705f6669787475726582666f626a656374820668726573706f6e736582666f757470757482118182108382820664726f6c65820669617373697374616e7482820664747970658206676d65737361676582820667636f6e74656e7482118182108382820664746578748206781f48656c6c6f2066726f6d207468652073696d756c61746564206d6f64656c2e828206647479706582066b6f75747075745f746578748282066b616e6e6f746174696f6e73821180826673746174757382138201820669636f6d706c657465648265757361676582138201820f85826c696e7075745f746f6b656e7382140c8274696e7075745f746f6b656e735f64657461696c73821382018210818282066d6361636865645f746f6b656e73820200826d6f75747075745f746f6b656e7382140482756f75747075745f746f6b656e735f64657461696c738213820182108182820670726561736f6e696e675f746f6b656e73820200826c746f74616c5f746f6b656e7382141006828363617070636a6f62820662613283636170706773657373696f6e820665616c69636583646578697400a6015021e649687ec5094e871d1561c4fd85800250d86e9f1831c6494789aa711badd7ddd303506c793d2fff3f39818152c34ffedee9810401058202581c82138269436f6d706c65746564820f818266737461747573820218c806828363617070636a6f62820662613283636170706773657373696f6e820665616c696365181982835021e649687ec5094e871d1561c4fd8580766d6f64656c2e657869743e7465726d696e616c2e696e8258198281687465726d696e616c818380018207820665616c69636500835093f83c16cbcdd7c379cf6f05bcea521e781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82581e82816d6578706c61696e5f7573616765818380018207820665616c69636500 a60702116d6578706c61696e5f75736167651282581e82816d6578706c61696e5f7573616765818380018207820665616c696365001364703a696e148183781a6d6f64656c2e6f75743e6578706c61696e5f75736167652e696e82568281656d6f64656c818380018207820665616c69636500021780 a6070211687465726d696e616c128258198281687465726d696e616c818380018207820665616c696365001364703a696e148183766d6f64656c2e657869743e7465726d696e616c2e696e82568281656d6f64656c818380018207820665616c69636500021780 seal 53fde566fb48ea019d3f0b337349482361780d44c0520e3714578b29dd0d4c72 ```
## Carry forward Previous: [Countdown](/examples/07-countdown.md). Use an explicit response type when a partner supplies usage or another business quantity. Keep each original sample and its provenance, including an honest absence. Compare this short adapter with the resident [Agent gateway](/examples/06-agent-gateway.md): the same typed-boundary discipline applies to two different interaction lifetimes. ## Limits The Lab scripts typed responses. Separate local wire tests, described in the [projected JSON qualification](https://github.com/rastok-io/rastok/blob/2e5128c76faf35cc879211138f429a4048608c77/docs/architecture/openai-responses-hydration.md), exercise full JSON deserialization; no paid OpenAI invocation is claimed. An API can change its payload and fail deserialization at runtime. No reporting engine, pricing rule or automatic inference retry is supplied. Missing usage remains unknown. The in-memory journal is not durable recovery. The boot-dependent profile also refuses `run --record`; use these versioned Lab traces rather than treating a deployment credential as a replay input. --- --- title: Privacy, secrets and measurements description: Classify typed data, bind credentials outside the graph, and retain exact business quantities on their original responses. url: https://docs.rastok.com/guide/08-privacy-secrets-and-measurements source_revision: v0.2.0-alpha --- # Privacy, secrets and measurements After this chapter you can distinguish a data annotation from its runtime interpretation, prepare the supported secret and privacy bindings, and locate a measurement in the original response. A value's type answers what it contains; its annotations state how that value must be handled or read. ## Declare metadata on a type An annotation-capable type uses `type Name = @struct { ... }`. Its argument fields are flat: scalars, enums and their nullable forms, rather than nested records or collections. The same declaration can describe ordinary data or typed metadata. Annotation arguments are checked plan constants. A user-declared annotation supplies descriptive metadata, not a handler or a security hook. Standard annotations have registered consumers in the checker, runtime and inspection tools. Reproducing a standard annotation's field shape does not acquire that authority. See [`docs/spec/annotations.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/annotations.md) §§1–5. ## Classify data where it enters the schema `examples/webhook-to-partner.rkg`, lines 3–7, identifies the email explicitly: ```rkg type Webhook = struct { event_id: string email: string @personal(identifier = true) amount: int } ``` `@personal` is a classification, independent of confidentiality. Its optional `identifier`, `special` and `criminal` flags describe the field's role. A personal-data plan requires an attested deployment profile covering its processing and recipients before execution. The supplied webhook profile is synthetic evidence for the demonstration, not authority for real processing. `@sensitive(level = ...)` orders `Internal`, `Confidential` and `Restricted`. Copies preserve policy; derived values conservatively carry relevant classification. The CLI and debugger redact before formatting. Redaction of a screen is not an erasure policy for stored data, nor a promise that arbitrary unannotated payloads are safe to share. ## Keep credentials outside DATA `@secret` describes a stronger handling class. The executable credential path is reference-based: a logical `secret("path")` at an admitted Connector setting is bound by the deployment, then resolved at the physical Driver boundary. The clear value is not an ordinary graph `Value`. Raw secret-bearing schemas on executable ports are refused; annotating a string is not a way to persist it safely in the journal. The current sites are specific: `HttpClient.url` accepts an exact `env()` reference and `HttpClient.auth_bearer` an exact `secret()` reference. Read `examples/agent-http.rkg`, lines 46–56: ```rkg connector model : HttpClient { url = env("MODEL_URL") auth_bearer = secret("showcase/model/token") method = "POST" codec = json json_profile = projected output out: ModelResponse timeout = duration("10s") max_body = "256 KiB" behavior = probabilistic } ``` The deployment JSON names the logical secret, environment-provider coordinate and immutable version. Supply the value out of band; its `_VERSION` companion must match. The graph, request digest and journal keep references, not the bearer bytes. `--deployment` supplies the same binding contract to real and simulated execution. General `env()` expressions at other sites are not part of this profile. See [`docs/spec/observability.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/observability.md) §5. ## Read quantities from original responses The adapter's response schema maps JSON members by name before committing the typed response. `examples/agent-http.rkg`, lines 8–14, supplies its measurement meaning alongside the numerical types: ```rkg type ResponseUsage = struct { input_tokens: ulong @measure(id = input_tokens, unit = "token") output_tokens: ulong @measure(id = output_tokens, unit = "token") total_tokens: ulong @measure(id = total_tokens, unit = "token") input_tokens_details: JsonObject? output_tokens_details: JsonObject? } ``` `@measure` has exactly `id` and `unit`. The integer or exact decimal field supplies the quantity; signed types can retain refunds or corrections. A currency is an ordinary unit. Each id has one unit throughout the plan. Missing usage supplies no sample; an observed zero remains evidence. The journal retains these values in their original envelopes. Read-only inspection pairs them with validated annotations and causal provenance. Retry's held attempts keep their own samples, even when no downstream Operator sees them. Consuming a held batch creates no second sample. Treat input, output and inclusive totals as separate observations, not as three quantities to add blindly. ## Generate types from an API description `rastok --resolve-open-api [--check]` discovers static HTTP endpoints, selects matching OpenAPI 3.0/3.1 documents and writes deterministic `openapi.generated.rkg` aliases. It leaves authored files untouched. `--check` writes nothing and refuses missing or stale generated source. Dynamic or ambiguous endpoints and schemas outside the lossless subset refuse by name. Choose where the generated types constrain ports; every actual response still has to conform at runtime. ## Summary Annotations classify typed data; deployment bindings supply external authority; measurements preserve original quantities. Reporting, automatic pricing, budgets and durable personal-data storage remain outside the [current alpha scope](/index.md#what-is-available-today). Normative details are in [`docs/spec/annotations.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/annotations.md), [`docs/spec/observability.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/observability.md) and [`docs/spec/schema-projections.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/schema-projections.md) §5. ## Next Continue with [Command line](/guide/09-command-line.md). Practice with the deployment profile in [Webhook to partner](/examples/04-webhook-to-partner.md), then compare absent and zero usage in the [HTTP model adapter](/examples/08-model-adapter.md). --- --- title: Execution and concurrency description: Distinguish instance ownership, concurrent external I/O and the execution model implemented by the current runtime. url: https://docs.rastok.com/reference/execution source_revision: v0.2.0-alpha --- # Execution and concurrency ## Current runtime The hosted runtime advances a program through one single-threaded Worker. It executes Operator transactions sequentially, not in parallel on several CPU cores. A Driver can have an external Call outstanding while the Worker processes other ready work. Network I/O and child processes can therefore overlap without parallel execution of DSL handlers. A transaction prepares its state changes and emissions, then commits them together. It does not wait for a partner response inside an Operator handler. A Connector's later response or timeout supplies another activation. A long-running Operator computation can delay other ready work; the alpha does not schedule it on a separate compute pool. ## Instances own state, not threads | Concept | Current meaning | |---|---| | Instance key | Selects a logical owner, such as one tenant or sensor; it does not allocate a thread or process | | Operator instance | Owns its mailbox and private `var` cells; its transactions run one at a time | | Connector instance | Owns its exchanges and Contract state; a Driver performs the external operations | | Graph instance | Owns containment and lifecycle, but has no application mailbox, handler or shared mutable state | | Lifetime | Determines when an instance closes; it is independent of key selection and physical placement | | Worker | Advances the execution, journal and selected Drivers; it is not created for each key | An unkeyed child belongs to its enclosing Graph instance. Keying the App by tenant therefore isolates its descendants even when each child omits an instance key. A `var` is private to the Operator instance that declares it; other Operators communicate through ports rather than reading that cell. See [Instances, state and time](/guide/06-instances-state-and-time.md). An outbound Call Connector instance holds one open Call at a time. The next request waits in that instance's mailbox, and its `timeout` already runs: the budget starts when the request is delivered to the Connector, not when the Call opens. A request queued behind a slow Call can therefore expire without having been sent; the journal shows it opening and closing with a timeout. For independent Calls, give each request its own instance. This per-instance ordering does not prevent I/O on different instances from overlapping. Mailboxes and Call capacities have bounds. A source Connector's proposal remains pending when its target mailbox is full; direct App input admission instead reports a capacity error. Neither commits an ingress before room is available. Adding an instance does not remove capacity bounds. The number of pending Calls is not a count of parallel Operator transactions. HttpServer handles inbound Calls, not that outbound mailbox queue. Its Driver bounds physical connections, requests and retained bytes. When the graph cannot admit a proposal, the Driver keeps it pending; an `ack` response of 202 follows admission, never precedes it. When its connection or request slots are full, the Driver waits for room rather than accepting unlimited work. A request exceeding a configured body or header size limit is refused before admission. Waiting does not guarantee that a client stays connected. Protocol refusals and failures remain distinct from admitted requests and their terminal outcomes. WebSocket Connectors and Process `service` use Sessions, not one Call per message. ## What the two-tenant example demonstrates In [Two tenants](/examples/03-two-tenants.md), Alice's first Call remains pending while Bob's Call completes. Alice's timeout and backoff belong to her instance, so Bob does not repeat his request. The Lab supplies both partners' behavior and advances the clock explicitly. This demonstrates independent progress and isolated Retry state, not multicore throughput. The corresponding real-world pattern can have several external requests outstanding. A Process Connector may start child processes under its Contract; that does not make every keyed Operator an operating-system process. ## Ordering and replay Deliveries within one instance mailbox are consumed in FIFO order. Independent instances have no application-level ordering guarantee between them. When external responses race, their admitted order can differ between live runs. The journal records the chosen order and causes. The Lab makes inputs, partner responses and time explicit, so a scenario can reproduce its journal. Diagnostic replay reads recorded facts without repeating external effects. Neither claim means that live partners must respond in the same order on every deployment. See [The Lab](/reference/lab.md) and [Running for real](/guide/05-running-for-real.md). ## Specified, not shipped | Capability | Boundary of the current implementation | Specification | |---|---|---| | A bounded pool of Workers across CPU cores | The hosted runtime uses one Worker; keyed instances are not scheduled across a pool | [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) §2 | | Distributed placement and reassignment | Virtual-shard mapping has a proof implementation, but the alpha does not deploy instances across Hosts or implement ownership leases | [`docs/spec/instances.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/instances.md) §9 | | A separate compute pool | Operator evaluation is synchronous; CPU-heavy work is not offloaded by the runtime | [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) §2 | These implementation limits do not change the ownership rule: one instance must never execute conflicting transactions concurrently. --- --- title: Command line description: Choose a Rastok command, supply its options, and distinguish read-only checks from real execution and file writes. url: https://docs.rastok.com/guide/09-command-line source_revision: v0.2.0-alpha --- # Command line After this chapter you can choose commands and interpret their exit status. Run examples from the checkout root. ## Help and version ```text rastok --help | -h | help rastok --version | -V | version ``` Help prints to stdout and exits successfully. `rastok --version`, `rastok -V` and `rastok version` print the same package version. Global help and version reject extra arguments. `rastok --help` prints that command's usage and options on stdout and exits successfully; `-h` is the same. Run `rastok --help` for the options of one command. Brackets mean optional, `|` separates alternatives, and `...` accepts multiple files in one compilation unit. ## Create a program: new ```text rastok new ``` `rastok new hello` creates `hello.rkg`: an App, a typed Operator and a Lab scenario. Names exclude paths and extensions. Existing files are never overwritten; follow-up commands are printed, not executed. ## Check a program: check ```text rastok check ... ``` ```sh rastok check examples/echo.rkg ``` Checks types, wiring and Contracts, then prints the Node count and semantic hash. It neither executes the App nor writes a plan file. Success does not prove partner availability or compatible physical Drivers. ## Run scenarios: simulate ```text rastok simulate ... [--deployment ] [--compare | --save ] [--ui [--ui-port ]] ``` ```sh rastok simulate examples/echo.rkg --compare examples/traces/echo ``` Simulation uses mocks and virtual time, not physical Drivers. Without `--ui`, it prints each scenario's `PASS` or `FAIL`, `simulation.scenario`, then totals. Direct scenarios use their Lab's name. A unit without a Lab refuses. - `--compare` reports each scenario's first difference from reviewed traces. Missing references fail. - `--save` creates or replaces reference files named `..rkc`. Review the semantic reason for the change; saving is not proof that expectations pass. - These options are exclusive. Neither selected: check expectations without reading or writing reference traces. - `--deployment` supplies the graph's boot values and attestations even with mocks. `--ui` requires `hosted-ui`, prints a token-bearing loopback URL and starts paused. `--ui-port` requires `--ui` and selects a nonzero TCP port; otherwise the OS chooses one. ## Execute the App: run ```text rastok run ... [--file-root ] [--deployment ] [--json-logs] [--record ] ``` ```sh printf 'hello\n' | rastok run examples/echo.rkg --record echo.rkr ``` Each stdin line enters `app.in` as a string, selecting the exact `string` branch of a union. Stdin does not decode JSON. An incompatible port and its type are reported before stdin is read. Drivers perform real I/O; the Lab does not run. A string prints bare. Any other value prints as one line of JSON, the same projection the Lab uses in its reports. Protected fields remain redacted. Raw payloads without a materialized value retain their byte-to-text rendering. With several declared output ports, every line keeps its `port: value` prefix. After EOF, `run` waits for open Calls and Sessions, not deadlines alone. An `HttpServer` keeps listening; read `listen` in the source. Ctrl-C stops it without a message. - `--file-root` enables the physical File Driver within an explicit root. - `--deployment` reads typed boot settings, secret coordinates, attestations and any Driver selection from a deployment JSON file. Secret material is supplied out of band, never as a CLI argument. - `--json-logs` exports structured events on stderr; outputs stay on stdout. The bounded exporter can drop observations; these logs are not a complete journal. Other diagnostics use stderr. - `--record` writes a diagnostic recording and refuses an existing path. Personal-data plans, nonempty deployment attestations and boot-dependent Connector settings refuse. Recordings are sensitive evidence, not durable restart storage. `run --ui` is not supported. Inspect a supported recording afterward instead. ## Inspect a recording: replay ```text rastok replay [--ui [--ui-port ]] ``` `rastok replay echo.rkr` prints App outputs in `run`'s format on stdout and a record-count/seal summary on stderr, without Driver I/O. `--ui` uses simulation's port rules and opens read-only recorded history. Missing source lines are explicit. Replay needs no original source and cannot execute the program or create a Lab scenario. ## Inspect capabilities: connectors ```text rastok connectors [--json] ``` Lists Contracts, modes, ports, settings, implementations, Lab bindings and untested cases, as text or `--json` on stdout. It constructs no Driver and probes no service; checker support does not prove deployment support. ## Resolve project schemas: --resolve-open-api ```text rastok --resolve-open-api [--check] ``` This matches static HTTP endpoints to OpenAPI 3.0/3.1 documents and writes `openapi.generated.rkg` types, leaving authored sources untouched. `--check` writes nothing and refuses missing or stale output. Unsupported or ambiguous schemas refuse. Generation cannot prove a live API honors its schema. The leading double dash is required. ## Exit status and streams - `0`: the requested operation succeeded, including explicit help or version. - `1`: compilation, execution, scenario, comparison or file operation failed. - `2`: a recognized usage error, such as a missing command or invalid option combination. Usage errors go to stderr, including a bare `rastok` invocation. Scenario failure details remain in the simulation report on stdout; do not detect success solely by whether stderr is empty. ## File formats - `.rkg`: program and Lab source. - `.rkp`: compiled plan package. - `.rkc`: causal reference for `simulate --compare`. - `.rkr`: execution recording for `replay`, without repeating external effects. ## Summary Check, then simulate before contacting partners; save only intentional baselines. Read the [alpha limits](/index.md#what-is-available-today), [`docs/spec/ui.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/ui.md) and [`docs/spec/schema-projections.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/schema-projections.md) §5. ## Next Practice with [Echo](/examples/01-echo.md). Next: [When the answer is lost](/guide/10-when-the-answer-is-lost.md). Previous: [Privacy](/guide/08-privacy-secrets-and-measurements.md). Deployment: [Running for real](/guide/05-running-for-real.md). --- --- title: When the answer is lost description: Read a Call terminal, distinguish a lost answer from a refused operation, and choose what to tell the caller. url: https://docs.rastok.com/guide/10-when-the-answer-is-lost source_revision: v0.2.0-alpha --- # When the answer is lost After this chapter you can distinguish “the partner said no” from “we never heard the answer.” Suppose you send a booking request. You wait, the deadline passes, and no receipt arrives. The room may still be booked. Starting again with a different reference could book a second room; telling the guest that nothing was booked could leave a reservation that nobody knows to cancel. ## What the terminal tells you A finite outbound Call has one terminal on its `exit` port. Losing the answer does not create a second port. It changes what you can conclude from the case: - **No answer arrives.** `TimeoutExpired` says the Call reached its deadline. It does not say where the partner was in its work. - **The answer cannot be used.** An HTTP client may receive an unreadable body (`DecodeFailed`), lose the exchange (`ProtocolFailed`), or reach the body limit (`BodyTooLarge`). A File or Process has different case names. Check the table in its [Connector contract](/reference/contracts.md). - **The runtime closes the Call without observing its end.** `OutcomeUnknown` preserves that uncertainty. Recovery does not silently send the request again. An outbound [HttpClient](/reference/connectors/http-client.md) can also produce `DecodeFailed` before sending a request that does not fit its codec. Read `data.message` after testing `data is DecodeFailed`: a request refusal names the input, while an unreadable response names the output or the declared field that did not fit. The message explains the refusal without copying the value. It is not a receipt: a partner may already have acted before sending an unreadable response. ## Three responses to the same timeout Choose what is safe for this particular operation. These choices can go to the same output as other cases; the important part is to name the case and decide what the output means. | Choice | What the booking program does | What its caller learns | |---|---|---| | Report uncertainty | Route `TimeoutExpired` and the other lost-answer cases to the branch that emits `Unknown`. | There is no receipt. The caller can decide whether to investigate. | | Read back | Send a separate lookup with the original booking reference and compare the returned receipt with the request. | A matching receipt confirms the booking without making another one. If the lookup also loses its answer, report the booking as unconfirmed. | | Retry with a key | Give the Call a stable `idempotency_key`, declare the partner's idempotence guarantee, and select `TimeoutExpired` in `Retry.on`. | The partner can recognize another attempt at the same operation. If the attempts run out, the last terminal still needs a decision. | A key identifies the operation. It does not by itself make the partner honor that key. In the [webhook example](/examples/04-webhook-to-partner.md) the contract with the partner supplies that guarantee. Read `examples/webhook-to-partner.rkg`, lines 93–95: ```rkg Retry.attempts = 2 Retry.on = [ServerError, TimeoutExpired, DnsFailed, ConnectFailed] Retry.delay = { kind = fixed; after = duration("1s") } ``` ## Read the warning If a route sends only `Completed` to a receipt handler and sends `_` to a failure handler, `rastok check` reports `W-MATCH-CATCHALL` on the underscore. It does the same for the match in the first Operator that receives the terminal through a simple route. The diagnostic lists the lost-answer cases that no arm names. An arm that tests `data is TimeoutExpired` names that case; the other cases can share one arm. The check follows nested matches. For example, `data is TimeoutExpired && retrying` does not cover a timeout when `retrying` is false. A wildcard that writes neither an output nor state discards the event and is not reported. A handler with no wildcard is not reported either. The check does not follow the value through another Operator. ## Summary A timeout is evidence about the answer, not the reservation. Name the uncertain outcomes and choose whether to report them, look up a receipt, or repeat an operation under a guarantee. A warning does not change the plan or its exit status. For implementation limits, see [What is available today](/index.md#what-is-available-today). ## Next Run the timeout scenario in [Webhook to partner](/examples/04-webhook-to-partner.md). Compare its terminal after a successful retry with the last terminal when the partner never answers. For the repetition rule, return to [Loops and retries](/guide/07-loops-and-retries.md). --- --- title: AI Agents description: Read the documentation, the examples and their reference traces from a coding assistant through Markdown twins, llms.txt, content negotiation and the agent index. url: https://docs.rastok.com/ai-agents source_revision: v0.2.0-alpha --- # AI Agents Every page of this site exists twice: as HTML for people, and as Markdown for assistants and scripts. An assistant that can fetch a URL can read the whole documentation, the examples and their reference traces from the same pinned source as this site. Nothing here runs a graph or changes a file. ## What an assistant can read | Address | Content | | --- | --- | | [/llms.txt](/llms.txt) | What Rastok is, a short vocabulary, and every page with its description, in reading order. | | [/llms-full.txt](/llms-full.txt) | The same index followed by the complete Markdown of every page. | | `.md`, such as [/getting-started.md](/getting-started.md) | The Markdown twin of one page. Example pages include their raw graph and reference trace. | | [/agent-index.json](/agent-index.json) | The text of every page and the list of examples, as the visible search uses them. | | `/examples/.rkg` | A raw example source from the pinned checkout, such as [/examples/echo.rkg](/examples/echo.rkg). | On Cloudflare, requesting a page's HTML address with `Accept: text/markdown` returns its Markdown twin. The plain Astro development server serves the `.md` files and the indexes; content negotiation runs in the Cloudflare Pages Worker. ## A working path, from nothing to a checked program 1. **Discover.** Read [/llms.txt](/llms.txt): what Rastok is, the vocabulary, every page, the specification and the example sources. 2. **Learn the syntax.** The normative grammar and the specification chapters are linked from `llms.txt` at the pinned revision; the [Reference](/reference/types) pages explain types, expressions, Contracts, Connectors, the Lab and the diagnostics in reading order. 3. **Read a complete program.** Each `/examples/.rkg` is a whole program with its Lab in the same file; start with [/examples/echo.rkg](/examples/echo.rkg), then [/examples/webhook-to-partner.rkg](/examples/webhook-to-partner.rkg) for Connectors, Retry and instances. 4. **Write and check.** `rastok new ` creates a file with a typed Operator and a Lab; `rastok check .rkg` compiles it and prints typed diagnostics with their codes, explained in [Diagnostics](/reference/diagnostics). 5. **Simulate.** `rastok simulate .rkg` runs every Lab scenario and reports `PASS` or the first difference; `--ui` opens the debugger. Install the CLI as described in [Getting Started](/getting-started). ## Point your assistant at it Give the assistant the address of `llms.txt` or of one page; it follows the links from there. In Claude Code, Codex or Cursor, fetching the URL is enough, no server or plugin to install. To write: open your preferred LLM harness or coding agent in an empty directory and give it a specification, for example: "Using https://docs.rastok.com/llms.txt, develop a Rastok application and its Lab that meet the following specification: \." The documentation tells it how to check and simulate what it wrote. To read: "Read https://docs.rastok.com/examples/04-webhook-to-partner.md and explain how the retry is bounded and what the reference trace proves." ## Public access These addresses are public. They require no login, no token and no account. No graph execution is provided. ---