From 5698cd0ee0b16d96621165ea6a50447d8a445705 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:36:58 -0800 Subject: [PATCH 1/5] fix: every YAML file is read by YAML 1.2.2, a setting of the host by one rule, and an upload by the pack's own reader The configuration reader: a plain scalar is resolved by the core schema of YAML 1.2.2 in both packs (the maintainer's ruling): true and false are the booleans, 010 is 10, and yes, on, 16_000, 1:30, 0b101, a date and the merge key are text or an ordinary key. It reads application.yml, rest.yaml, app-log-context.yaml and the MCP binding's file. As text a boolean is true or false and a float keeps its point. A key with no value and one its references leave empty take the default; a reference sees an override; a reference loop is logged and has no value. Settings of the host follow the round's rule and stop the start by name: rest.automation, rest.server.port, rest.upload.max.bytes, event.stream.keep.alive, an entry's timeout, otel.forwarding, app.log.context. REST automation and the host: one upload reader in both packs, pinned by 76 shared cases over the reader and over HTTP, with filename* and name* as RFC 5987 writes them; the client returns an edge's JSON error as the failure it carries; a reply the wire codec refuses is the engines' 500; a refusal while the request is read is traced. The guides say how a file is read and recommend YAML 1.2.2 to whoever writes one. The OTLP exporter's except clause names no exception twice: a timeout is an OSError. Co-Authored-By: Claude Fable 5.2 --- docs/guides/ai-agent-guide.md | 5 + docs/guides/config-logging-actuators.md | 3 +- docs/guides/configuration-reference.md | 99 +- docs/guides/function-patterns.md | 5 +- docs/guides/http-surface-reference.md | 12 +- docs/guides/rest-automation.md | 48 +- docs/guides/streaming.md | 3 +- docs/llms.txt | 2 +- extensions/mcp-binding/README.md | 3 + extensions/mcp-binding/mcp_binding.py | 26 +- src/mercury_composable/async_http_request.py | 14 +- src/mercury_composable/client.py | 35 +- src/mercury_composable/config.py | 321 ++- src/mercury_composable/event_stream.py | 31 +- src/mercury_composable/log_context.py | 33 +- src/mercury_composable/otel/__init__.py | 16 +- src/mercury_composable/otel/export.py | 5 +- src/mercury_composable/rest_automation.py | 162 +- src/mercury_composable/rest_routing.py | 295 ++- src/mercury_composable/server.py | 109 +- tests/test_client.py | 81 +- tests/test_config.py | 199 +- tests/test_log_context.py | 63 +- tests/test_mcp_binding.py | 15 + tests/test_otel_forwarder.py | 33 +- tests/test_rest_automation.py | 364 ++- tests/test_server.py | 170 ++ tests/vectors/config-vectors.json | 2409 ++++++++++++++++++ tests/vectors/rest-automation-vectors.json | 1778 ++++++++++++- 29 files changed, 5931 insertions(+), 408 deletions(-) create mode 100644 tests/vectors/config-vectors.json diff --git a/docs/guides/ai-agent-guide.md b/docs/guides/ai-agent-guide.md index 7e8deb4..673d1cd 100644 --- a/docs/guides/ai-agent-guide.md +++ b/docs/guides/ai-agent-guide.md @@ -22,6 +22,11 @@ authored on the engine — use the 3. Function is stateless. State belongs to the calling flow/graph. 4. Orchestration-shaped logic (sequencing, retries, branching) → STOP; author an Event Script flow or MiniGraph graph on the engine instead. +5. Every YAML file (`application.yml`, `rest.yaml`) is YAML 1.2.2: write `true`/`false`, plain + decimal numbers, `0x` for hex, and quotes around any text that looks like a boolean, a number, + a date or null. Never `yes`/`no`/`on`/`off`, `010`, `0o10`, `0b101`, `1:30`, `16_000`, an + unquoted date or the merge key `<<` — the Java engine reads those another way + ([the rule](configuration-reference.md#how-a-yaml-file-is-read)). ## The contract diff --git a/docs/guides/config-logging-actuators.md b/docs/guides/config-logging-actuators.md index f22ca1d..ef5abc2 100644 --- a/docs/guides/config-logging-actuators.md +++ b/docs/guides/config-logging-actuators.md @@ -82,7 +82,8 @@ otel.service.name: 'my-python-functions' ``` With `otel.forwarding=true` (the switch is the only thing that turns it on — `false` by -default, and `-Dotel.forwarding=true` at run time is enough), the host also hands each +default, `-Dotel.forwarding=true` at run time is enough, and a value that is neither `true` +nor `false` stops the start by name), the host also hands each dataset to the engines' extension route `distributed.trace.forwarder`, where the built-in forwarder registers itself at start-up (private, two workers; an application that registers its own function on that route wins). Each dataset becomes **one OpenTelemetry span carrying diff --git a/docs/guides/configuration-reference.md b/docs/guides/configuration-reference.md index 144e3d2..fe65537 100644 --- a/docs/guides/configuration-reference.md +++ b/docs/guides/configuration-reference.md @@ -16,32 +16,117 @@ keywords: [configuration, reference, keys, substitution, overrides] 2. The configuration file: `resources/application.yml` | `.yaml` | `.properties` next to the application file (the file `mercury-serve` is given, or the script `python app.py` ran), never in the working directory; or `--config `. -3. `${ENV_VAR:default}` substitution inside values: environment first, then a base - configuration key of that name, then the default. +3. `${ENV_VAR:default}` substitution inside values: the environment variable first, then the + configuration key of that name — a `-D` override of it before the file's value, as a key is + read — then the default. A reference that leads back to a key being resolved is logged + (`Config loop for 'key' detected`, as the engines log it) and has no value, so its default + stands. A value its references leave empty is no value either, as in the Java engine: with + `llm.effort: '${LLM_EFFORT:}'` and the variable unset, the key reads as its default — the + idiom for an optional setting — while an empty text written as one (`key: ''`) stays one. + +## How a YAML file is read + +Every YAML file of the pack — `application.yml`, `rest.yaml`, `app-log-context.yaml`, an +extension's own file — is read by **YAML 1.2.2**, the same way by the Python pack and the Node.js +pack. A scalar written without quotes is resolved by the core schema of the +specification (section 10.3.2), its rows tried in this order: + +| Written | Read as | +|---------|---------| +| nothing, `~`, `null`, `Null`, `NULL` | no value: the key reads as a key that is not there, so its default applies | +| `true`, `True`, `TRUE`, `false`, `False`, `FALSE` | a boolean | +| `[-+]?[0-9]+` — `16000`, `-5`, `010` | an integer in base 10, exact at any size: `010` is 10 | +| `0o[0-7]+` — `0o17` | an integer in base 8 | +| `0x[0-9a-fA-F]+` — `0x1F` | an integer in base 16 | +| `[-+]?[0-9]+(\.[0-9]*)?([eE][-+]?[0-9]+)?` with a point or an exponent, or `[-+]?\.[0-9]+([eE][-+]?[0-9]+)?` — `1.5`, `16000.0`, `1e3`, `.5` | a float | +| `.inf`, `.Inf`, `.INF`, also with a sign; `.nan`, `.NaN`, `.NAN` | a float | +| anything else, and anything in quotes | text | + +So `yes`, `no`, `on`, `off`, `y` and `n`, a number with an underscore (`16_000`), in base 2 +(`0b101`) or in base 60 (`1:30`), `-0x10`, a date (`2026-11-30`), `=` and `<<` are text, and `<<` +as a key is a key like any other, not the merge key. A switch or a flag written `yes` is refused by +name (`rest.automation must be true or false`), never read as on and never as off. Under an +explicit tag a scalar is valid when the tag is one of the core schema's (`!!str`, `!!int`, +`!!float`, `!!bool`, `!!null`) and its content one of that tag's rows; a file with any other tag +(`!!binary`, `!!timestamp`, `!!set`) does not load. + +### Write YAML 1.2.2, and none of the additional syntax of YAML 1.1 + +This is the recommendation for whoever writes a file, a developer or an AI assistant. The Java +engine's reader (SnakeYAML) reads YAML 1.1 and still accepts the older syntax, so a file that uses +it reads one way in the Java engine and another way in the packs. The Rust engine reads YAML 1.2 as +well; its library departs from the core schema in three spellings, which the table shows: + +| Do not write | The Java engine reads | The Rust engine reads | The packs read | Write | +|--------------|-----------------------|-----------------------|----------------|-------| +| `yes`, `no`, `on`, `off` | a boolean | text | text | `true`, `false` | +| `010`, `08` | 8 (base 8), text | text | 10, 8 | `10`, `8` — or `'010'` when it is text | +| `0o10` | text | 8 | 8 | `8` | +| `0b101` | 5 | 5 | text | `5` | +| `-0x10` | -16 | -16 | text | `-16` | +| `1:30` | 90 (base 60) | text | text | `90` — or `'1:30'` when it is text | +| `16_000` | 16000 | text | text | `16000` | +| `2026-11-30` | a date, written in the time zone of its JVM | text | text | `'2026-11-30'` | +| `<<: *base` | the merge key | a key named `<<` | a key named `<<` | the keys themselves | + +`yes`/`no`/`on`/`off`, `0b101`, `1:30`, `16_000` and the merge key are syntax of YAML 1.1 only. A +number with a leading zero (`010`, `08`), `0o10` and an unquoted date are valid YAML 1.2.2 and are +to be avoided all the same, because the Java engine reads them another way and the Rust engine keeps a +number with a leading zero as text. `y` and `n`, booleans +in YAML 1.1 itself, are text in every runtime. The forms every runtime reads alike: `true` and `false`; a plain decimal number without a leading zero, an underscore or a +colon (`16000`, `-5`, `1.5`, `1e3`); `0x` for base 16 (`0x1F`); and quotes around any text that +could be read as a boolean, a number, a date or no value (`'true'`, `'010'`, `'1e3'`, +`'2026-11-30'`, `'null'`). + +### The text of a value + +As text — what `get_property` returns, and what a reference inside a longer text is replaced by — a +boolean is `true` or `false` and a float keeps its point (`1.0`, never `1`), so +`info.app.version: 1.0` reads `1.0` in both packs; a float is written as Python writes one, which +is the Java engine's text too between 0.001 and 10,000,000. A mapping key YAML read as something +other than text (`True:`, `8080:`) is the text of that value (`true`, `8080`). A tab is read as two +spaces, as the Java engine reads a file, so one indented with tabs loads. A file whose document is +not a mapping has no keys, and the last of two equal keys stands. + +## A number, a duration and a switch + +The settings of the host read these by one rule, the same in both packs; a value that is none of +them stops the start by name instead of being read as off or as a default: + +- **a whole number** — a number with a whole value (`16000`, `16000.0`), or text of the digits + `0`-`9` with white space around them at most, up to 9007199254740991. A sign, an underscore, a + point or an exponent in text and a digit of another script are refused + (`rest.upload.max.bytes must be a whole number >= 0`); +- **a duration** — such a number, in seconds, or the number and, right after it, one of `ms`, `s`, + `m`, `h`, `d`: `30`, `30s`, `500ms`, `2m` + (`event.stream.keep.alive must be a duration such as 30s, 2m or 500ms (seconds, ms, s, m, h, d), or 0 for none`); +- **a switch** — the boolean `true` or `false`, or that text in any letter case; no value and an + empty one are the default (`rest.automation must be true or false`). ## Well-known keys (shared with the engines) | Key | Meaning | Default | |-----|---------|---------| | `application.name` | application identity in logs, `/info` and `/health` | `application` | -| `rest.server.port` | Event API + actuator port | `8085` | +| `rest.server.port` | Event API + actuator port: a whole number up to 65535, `0` for one the system picks | `8085` | | `log.format` | `text`, `json` (pretty-printed) or `compact` (single-line JSONL) | `text` | | `log.level` | log level; the `LOG_LEVEL` environment variable wins | `INFO` | +| `app.log.context` | the application log context: a `context` block on every structured log line inside a traced request ([guide](function-patterns.md#trace-context-and-span-lineage)); a switch — `false` opts out, any value but `true` or `false` stops the start | `true` | | `info.app.version` | version reported by `/info` | package version | | `info.app.description` | description reported by `/info` | `application.name` | | `show.env.variables` | opt-in list of environment variables shown by `/env` | (empty) | | `show.application.properties` | opt-in list of configuration keys shown by `/env` | (empty) | | `mandatory.health.dependencies` | routes of health check functions that decide `/health` | (empty) | | `optional.health.dependencies` | health check routes reported but never affecting status | (empty) | -| `rest.automation` | REST automation on: the entries of `rest.yaml` served in front of the functions ([guide](rest-automation.md)) | `false` | +| `rest.automation` | REST automation on: the entries of `rest.yaml` served in front of the functions ([guide](rest-automation.md)); a switch — any value but `true` or `false` stops the start | `false` | | `yaml.rest.automation` | the one location of `rest.yaml`: `classpath:` the resources folder, `file:` an absolute path, a relative path under the application file's folder | `classpath:/rest.yaml` | -| `rest.upload.max.bytes` | the bound on one upload: its files and its text fields together, counted in bytes (413 beyond it) | `16777216` | +| `rest.upload.max.bytes` | the bound on one upload: its files and its text fields together, counted in bytes (413 beyond it); a whole number | `16777216` | | `http.trace.id.header` | the trace-id header a traced entry reads when no W3C `traceparent` arrives (`trace.id.header` overrides it per entry) | `X-Trace-Id` | | `http.correlation.id.header` | the business correlation-id header, always ensured and echoed (`correlation.id.header` per entry) | `X-Correlation-Id` | | `http.traceparent.header` | a custom name for the W3C `traceparent` header, read only when the standard one is absent (`traceparent.header` per entry) | `traceparent` | -| `event.stream.keep.alive` | the keep-alive comment interval of a Server-Sent Events reply (`/api/event` and streaming entries); `0` disables | `30s` | +| `event.stream.keep.alive` | the keep-alive comment interval of a Server-Sent Events reply (`/api/event` and streaming entries): a duration up to 2147483647 ms (about 24.8 days, the longest a timer of the Node.js pack holds); `0` disables | `30s` | | `static.html.folder` | the folder of static web content the host serves for the paths nothing else claims — relative to the application file's folder ([guide](config-logging-actuators.md#static-content-the-engines-public-folder)) | `resources/public` | -| `otel.forwarding` | the OpenTelemetry forwarder's master switch ([guide](config-logging-actuators.md#distributed-tracing-the-opentelemetry-forwarder-opt-in)) | `false` | +| `otel.forwarding` | the OpenTelemetry forwarder's master switch ([guide](config-logging-actuators.md#distributed-tracing-the-opentelemetry-forwarder-opt-in)); a switch — any value but `true` or `false` stops the start | `false` | | `otel.exporter.otlp.endpoint` | the OTLP/HTTP traces URL including the signal path | `http://localhost:4318/v1/traces` | | `otel.exporter.otlp.headers` | request headers, `k=v` or `k: v`, comma-separated (re-read per export) | (none) | | `otel.exporter.otlp.timeout` | per-export timeout in milliseconds | `10000` | diff --git a/docs/guides/function-patterns.md b/docs/guides/function-patterns.md index ebb607f..eedab4a 100644 --- a/docs/guides/function-patterns.md +++ b/docs/guides/function-patterns.md @@ -132,8 +132,9 @@ engines' app-log-context feature, on by default) - the standard trace context `parentSpanId`, `service`, `timestamp`) - so application logs and the distributed-trace records correlate in one aggregation. Customize with your own `resources/app-log-context.yaml` (`context:` section mapping output keys -to reserved `$tokens` or constants, `${ENV:default}` supported), opt out with -`app.log.context=false`, and add per-request key-values from a handler with +to reserved `$tokens` or constants, `${ENV:default}` supported; read as every YAML +file of the pack is), opt out with `app.log.context=false` (a switch: any value but +`true` or `false` stops the start), and add per-request key-values from a handler with `update_context("tenant", "acme")` (a logging-only sink; reserved keys are guarded; `None` removes). diff --git a/docs/guides/http-surface-reference.md b/docs/guides/http-surface-reference.md index a274983..db616b8 100644 --- a/docs/guides/http-surface-reference.md +++ b/docs/guides/http-surface-reference.md @@ -17,11 +17,11 @@ Mirrors the engines' `event.api.service`: | Aspect | Behavior | |--------|----------| | Request body | event envelope bytes ([standard wire format](https://accenture.github.io/mercury-composable/guides/event-envelope-wire-format/)) | -| `x-ttl` header | execution bound in ms (floor 1000) | +| `x-ttl` header | execution bound in ms (floor 1000); a value that is no whole number counts as none | | `x-async: true` | drop-n-forget → HTTP 202 with ack envelope `{type: async, delivered: true, time}` | | Reply | always envelope bytes, `content-type: application/octet-stream` | | Handler outcome | rides **HTTP 200** with the status inside the envelope (including AppException and unexpected errors) | -| Transport failures | set the HTTP status too: 400 undecodable / missing route field, 403 private target, 404 unknown route (`Route X not found`), 408 timeout (`Timeout for N ms`), 413 a body over the 16 MiB the host reads into memory (`Request body exceeds 16777216 bytes`) | +| Transport failures | set the HTTP status too: 400 undecodable / missing route field, 403 private target, 404 unknown route (`Route X not found`), 408 timeout (`Timeout for N ms`), 413 a body over the 16 MiB the host reads into memory (`Request body exceeds 16777216 bytes`), 500 a reply the wire codec refuses (`Reply cannot be rendered`; in band, as the terminal frame, once a stream has started). Behind a `rest.yaml` entry the edge's own refusals (401, 413) are the engines' JSON error body, which the pack's client and the engines' read as the failure it carries | | Header hygiene | inbound `x-event-api` and `my_*` removed; the `my_cid` tag becomes the read-only `my_correlation_id` header (local bus deliveries inject the same view). Outbound, the client stamps the current context's business correlation-id back onto the event as the `my_cid` tag — the engines' PostOffice parity, so the business correlation-id continues across every hop | | `accept: text/event-stream` | streaming-capable call to an interceptor target: a streamed reply rides the same call as SSE in the envelope-mode dialect; a single-shot reply stays byte-identical; a streaming reply to a NON-accepting caller → 406 `Streaming function requires a caller that accepts text/event-stream`. See [Event Streaming](streaming.md) | @@ -57,10 +57,10 @@ first, in the engines' grammar; `POST /api/event` and the actuators are the defa | Matching | the engines' precedence — the most specific route wins, `{param}` and a trailing `*`; a known path under another method → 405 `Method not allowed`; an unknown path → 404 `Resource not found`; `OPTIONS` → 204 with the entry's CORS `options` lines, 405 without a CORS block | | Request to the function | the whole request as the `AsyncHttpRequest` map — method, url, headers (lowercased, after the request transform), path and query parameters (a form's fields among them), the body parsed by its content type (JSON → map or list, text types → text, else bytes), cookies, the `session` map an authentication function left; `x-ttl` carries the entry's timeout in ms | | Reply | a returned value is the body; a returned `EventEnvelope` sets the status and headers (`set-cookie` values split on `\|`); the content type is the function's or negotiated from `Accept` (`text/html` wraps a map in the HTML shell; no `Accept` → no content type); a map or list is pretty-printed JSON with `null` entries omitted | -| Errors | the engines' body below with `content-type: application/json`: an `AppException` from the function or the authentication function (anything but `true` from the latter → 401 `Unauthorized`); 408 `Timeout for N ms` at the entry's timeout (1 s–5 min, 30 s default; an inbound `x-ttl` wins); 503 `Service X not reachable` for an unregistered function; 413 `Upload exceeds N bytes`; 413 `Request body exceeds 16777216 bytes` for a body over the 16 MiB the host reads into memory; 500 `Reply cannot be rendered` for a reply the serializer refuses | -| Correlation and tracing | `X-Correlation-Id` (or `http.correlation.id.header`) always ensured and echoed, delivered as `my_correlation_id`; with `tracing: true` a W3C `traceparent`, else `X-Trace-Id` (`http.trace.id.header`), else a fresh id, and the `http.request` record plus the function's round-trip record | -| `stream: true` | an interceptor's segments rendered progressively: Server-Sent Events (`event:`/`data:` frames, `event: done` at the end, `event: error` in band, `: ping` keep-alives every `event.stream.keep.alive`) for a `text/event-stream` head or `Accept`, chunked text or JSON lines otherwise; the entry's timeout is the idle allowance, the head's `x-ttl` overrides it; a keep-alive that cannot be written ends the stream; a segment the serializer refuses fails it in band with 500 `Reply cannot be rendered` | -| `upload: true` | a `POST` entry's `multipart/form-data` files in the request map (`filename`, `file_type`, `file_length`, `upload`, `size`, bytes in `contents`), the form's text fields as query parameters, no body; the files and the text fields together, counted in bytes, within `rest.upload.max.bytes` (16 MiB); a part that is multipart itself → 400 `Upload takes text fields and files, not a nested multipart part` | +| Errors | the engines' body below with `content-type: application/json`: an `AppException` from the function or the authentication function (anything but `true` from the latter → 401 `Unauthorized`); 408 `Timeout for N ms` at the entry's timeout (1 s–5 min, 30 s default; an inbound `x-ttl` that is a whole number wins); 503 `Service X not reachable` for an unregistered function; 413 `Upload exceeds N bytes` and the 400s of an upload a form does not send; 413 `Request body exceeds 16777216 bytes` for a body over the 16 MiB the host reads into memory; 500 `Reply cannot be rendered` for a reply the serializer refuses | +| Correlation and tracing | `X-Correlation-Id` (or `http.correlation.id.header`) always ensured and echoed, delivered as `my_correlation_id`; with `tracing: true` a W3C `traceparent`, else `X-Trace-Id` (`http.trace.id.header`), else a fresh id, and the `http.request` record plus the function's round-trip record; a refusal while the body is read (400, 413) leaves the `http.request` record too | +| `stream: true` | an interceptor's segments rendered progressively: Server-Sent Events (`event:`/`data:` frames, `event: done` at the end, `event: error` in band, `: ping` keep-alives every `event.stream.keep.alive`) for a `text/event-stream` head or `Accept`, chunked text or JSON lines otherwise; the entry's timeout is the idle allowance, the head's `x-ttl` (a whole number of seconds) overrides it; a keep-alive that cannot be written ends the stream; a segment the serializer refuses fails it in band with 500 `Reply cannot be rendered` | +| `upload: true` | a `POST` entry's `multipart/form-data` files in the request map (`filename`, `file_type`, `file_length`, `upload`, `size`, bytes in `contents`), the form's text fields as query parameters, no body; the files and the text fields together, counted in bytes, within `rest.upload.max.bytes` (16 MiB). Read as a browser's form sends it, the same in both packs: a part is `form-data` with a `name` and, for a file, a `filename` (an empty one included), either also in the extended form `name*` / `filename*` (RFC 5987: UTF-8 or ISO-8859-1, percent-encoded), which wins; a file's type is its `Content-Type` as written or `application/octet-stream`, its bytes as they arrived; a text field is UTF-8, or the ISO-8859-1 or US-ASCII its part declares. Anything else → 400 by name: a part that is multipart itself (`Upload takes text fields and files, not a nested multipart part`), a part without a name, a `name*` or `filename*` that is malformed, in another charset or not the text it declares, a `Content-Transfer-Encoding` other than `7bit`, `8bit`, `binary`, a `Content-Encoding`, another charset, a field that is not the text it declares, a body not delimited as declared (`Invalid multipart body - ...`) | | Precedence | a `rest.yaml` entry, then an extension's mounted routes (`Platform.add_routes`), then the static folder (under the `static-content` block's `no-cache-pages` and `filter`), then the error signature below | ## Static content diff --git a/docs/guides/rest-automation.md b/docs/guides/rest-automation.md index 579de86..7591040 100644 --- a/docs/guides/rest-automation.md +++ b/docs/guides/rest-automation.md @@ -73,11 +73,19 @@ headers: - "Cache-Control: no-cache, no-store" ``` -`${key:default}` in any value resolves against the configuration, as in the engines. A flag — -`tracing`, `stream`, `upload` — is `true` or `false`, read as the Java engine reads it: the +`${key:default}` in any value resolves against the configuration, as in the engines: the +environment variable of that name, then the configuration key — a `-Dkey=value` override of it +before the file's value — then the default. The file itself is read as `application.yml` is, by +YAML 1.2.2 ([the rule](configuration-reference.md#how-a-yaml-file-is-read)): a boolean is `true` +or `false`, `yes` and `on` are text, `1e3` is a number, `1_0` and `1:30` are text, a date is the +text as written. A flag — `tracing`, `stream`, `upload` — is `true` or `false`: the boolean, or the text in any letter case, which is what a reference such as `${TRACING:true}` -resolves to. Left out or empty it is off; any other value fails the start by name -(`rest[0] 'tracing' must be true or false`) rather than leave the flag off without a word. At the end +resolves to and what the Java engine takes too. Left out or empty it is off; any other value fails the start by name +(`rest[0] 'tracing' must be true or false`) rather than leave the flag off without a word. A +`timeout` is a whole number of seconds, or such a number and, right after it, one of `ms`, `s`, +`m`, `h`, `d` (`30s`, `2m`, `1500ms`); a value that is neither fails the start by name too +(`rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)`), where +the Java engine reads it as one second without a word. At the end of the boot the host announces every live entry — `REST [GET] /api/hello/{name} -> hello.rest` — and skips, with a warning, an entry whose function is not registered: never a live URL without a function behind it. @@ -143,12 +151,15 @@ unchanged — a flow binding apart — and behaves the same: the trace-id header (`http.trace.id.header`, `X-Trace-Id`), else a fresh id, and leaves the `http.request` record and the function's round-trip record the engines leave, so the [OpenTelemetry forwarder](config-logging-actuators.md#distributed-tracing-the-opentelemetry-forwarder-opt-in) - exports the request as a SERVER span with the function beneath it. An entry may rename its + exports the request as a SERVER span with the function beneath it. A request the edge refuses + while it reads the body — a malformed upload, a body over a limit — leaves the `http.request` + record too, with the status and the message, as the engines record a traced request once its + trace is resolved. An entry may rename its headers for a legacy caller with `trace.id.header`, `correlation.id.header` and `traceparent.header`. - **Timeout** — the entry's `timeout` (1 s to 5 min, 30 s by default; the `/api/event` default entry keeps the engines' 60 s) rides the request as `x-ttl` in milliseconds and answers 408 - `Timeout for N ms` when it expires; an inbound `x-ttl` wins. + `Timeout for N ms` when it expires; an inbound `x-ttl` that is a whole number wins. - **Headers** — the entry's `headers` block drops, keeps or adds request and response headers (`keep` takes precedence over `drop`, the Java rule); its `cors` block's `headers` lines ride every response. @@ -251,8 +262,26 @@ read with `request.files()` as `UploadedFile(name, content_type, size, tag, cont text fields become query parameters and the body stays absent, as in the Java engine. The files and the text fields of one upload together, counted in bytes, may not exceed `rest.upload.max.bytes` (16 MiB by default) — 413 `Upload exceeds N bytes` the moment they do, before anything is -delivered. A malformed body is 400, and so is a part that is multipart itself: -`Upload takes text fields and files, not a nested multipart part`. +delivered. + +The body is read by the pack's own reader, the same in the Python and the Node.js pack, as a +browser's form sends one: parts delimited by the boundary the content type declares, each +`Content-Disposition: form-data` with a `name` and, for a file, a `filename` — a file input left +empty arrives as a file with an empty name and no bytes. A name or a filename may also come in the +extended form a client writes for one that is not ASCII (`filename*=UTF-8''caf%C3%A9.txt`, RFC +5987: UTF-8 or ISO-8859-1, the bytes percent-encoded), which wins over the plain parameter of its +name. A file's type is its `Content-Type` as +written, `application/octet-stream` without one, and its bytes are the bytes that arrived. A text +field is UTF-8, or the ISO-8859-1 or US-ASCII its part declares, and a field named `_charset_` is +a field like any other. What a form does not send is a 400 that names it: a part that is multipart +itself (`Upload takes text fields and files, not a nested multipart part`), a part without a name, +an extended parameter that is malformed, in another charset or not the text it declares +(`Upload takes a part's filename* in UTF-8 or ISO-8859-1, not in 'Windows-1252'`), a +`Content-Transfer-Encoding` other than `7bit`, `8bit` or +`binary` and any `Content-Encoding` (`Upload takes the bytes of a part as they are, not a +Content-Encoding of 'gzip'`), a field in another charset or one that is not the text it declares +(`Upload text field 'note' is not UTF-8`), and a body that is not delimited as declared +(`Invalid multipart body - the closing delimiter is missing`). A non-multipart body on such an entry, and a multipart body on an entry without the flag, dispatch as any other body. The LLM helper's `llm.upload` — documents saved into the attachments root for a model to read — is the shipped example. @@ -264,7 +293,8 @@ A `GET` or `HEAD` no entry claims is served from the `static-content` block of `rest.yaml`: the `no-cache-pages` (default `/` and `/index.html`) are served `Cache-Control: no-cache, no-store`, and the `filter` function sees every matching static request first — its reply headers ride the response, a status other than 200 (a 302 to a sign-in -page) passes through, and a filter that fails lets the file be served. +page) passes through, and a filter that fails lets the file be served. A reply of its own that +cannot be rendered is answered as any other: 500 `Reply cannot be rendered`. ```yaml static-content: diff --git a/docs/guides/streaming.md b/docs/guides/streaming.md index d91d28b..09e3fac 100644 --- a/docs/guides/streaming.md +++ b/docs/guides/streaming.md @@ -65,7 +65,8 @@ byte-identical to a normal RPC reply; idle expiry fails the stream in-band with standard 408 error body. The `x-ttl` request header (ms) is the idle allowance between segments — your `first(..., ttl_seconds=...)` can extend it for the whole stream. While the producer is quiet, the host emits `: ping` keep-alive comments -(`event.stream.keep.alive`, the engines' config key — default 30s, `0` disables). +(`event.stream.keep.alive`, the engines' config key — default 30s, `0` disables; a whole number +of seconds or a duration such as `500ms` or `2m`, and a value that is neither stops the start). ## Consume a stream diff --git a/docs/llms.txt b/docs/llms.txt index 3b8d3a6..a448abe 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -29,6 +29,6 @@ - [Join a Knowledge Graph](https://accenture.github.io/mercury-python/guides/join-knowledge-graph/): graph.task to a declarative target (engines >= v4.11.11), deadlines, the error.* contract. ## Reference -- [Configuration Reference](https://accenture.github.io/mercury-python/guides/configuration-reference/): every well-known key, resolution order, substitution syntax. +- [Configuration Reference](https://accenture.github.io/mercury-python/guides/configuration-reference/): every well-known key, resolution order, substitution syntax, and how a YAML file is read: YAML 1.2.2 — write `true`/`false`, plain decimal numbers and quoted text; never the additional syntax of YAML 1.1 (`yes`/`no`/`on`/`off`, `010`, `0b101`, `1:30`, `16_000`, an unquoted date, the merge key `<<`), which the Java engine reads another way. - [HTTP Surface Reference](https://accenture.github.io/mercury-python/guides/http-surface-reference/): /api/event protocol, actuator shapes, the REST automation entries' behaviour (matching, errors, streaming, upload, precedence), error signature, content types. - [Release Notes](https://github.com/Accenture/mercury-python/blob/main/CHANGELOG.md) diff --git a/extensions/mcp-binding/README.md b/extensions/mcp-binding/README.md index 89511c2..d4668c1 100644 --- a/extensions/mcp-binding/README.md +++ b/extensions/mcp-binding/README.md @@ -60,6 +60,9 @@ Event-over-HTTP entry on the engine. ## The server file `mcp.servers` names the file (default `mcp-servers.yml` in the resources folder; a relative path is read from there). +The file is read as every YAML file of the pack is, by YAML 1.2.2 (`yes` and `on` are text, `010` is ten), and a value +written without quotes that is a boolean or a number reaches the server as the text a setting reads (`true`, `1.0`), +the same from both packs; quote a value that must stay as written. It holds what is environment-specific, never the tools: ```yaml diff --git a/extensions/mcp-binding/mcp_binding.py b/extensions/mcp-binding/mcp_binding.py index 996fe31..7022396 100644 --- a/extensions/mcp-binding/mcp_binding.py +++ b/extensions/mcp-binding/mcp_binding.py @@ -54,8 +54,6 @@ async def mermaid_render(_headers, body): from dataclasses import dataclass, field from typing import Any -import yaml - try: import httpx2 from mcp import ClientSession, types @@ -68,6 +66,7 @@ async def mermaid_render(_headers, body): ) from missing_sdk from mercury_composable import AppException, Body, app_config, get_logger, platform, preload +from mercury_composable.config import load_yaml, property_text log = get_logger(__name__) @@ -193,12 +192,19 @@ def tool_as_plain(tool: types.Tool) -> dict[str, Any]: def _resolve(value: Any) -> Any: """``${VAR}`` and ``${VAR:default}`` placeholders from the environment or the configuration, the - pack's rule for every setting; the resolved value is never logged.""" + pack's rule for every setting, as the text a setting reads; the resolved value is never logged.""" if isinstance(value, str): - return app_config().resolve_text(value) + return app_config().resolve_property(value) return value +def _text(value: Any) -> str: + """A value of the server file as text. The file is read as every YAML file of the pack is, so a + value written without quotes may be a boolean or a number: it is the text a setting reads + (``true``, ``1.0``), the same in the Node.js twin.""" + return property_text(value) + + def _str_map(server: str, key: str, value: Any) -> dict[str, str]: if value is None: return {} @@ -209,7 +215,7 @@ def _str_map(server: str, key: str, value: Any) -> dict[str, str]: text = _resolve(item) if text is None or text == "": raise BindingError(f"MCP server {server}: {key}.{name} resolves to nothing - set the variable it names") - resolved[str(name)] = str(text) + resolved[str(name)] = _text(text) return resolved @@ -244,9 +250,9 @@ def _stdio_server(name: str, value: dict[str, Any], timeout_ms: int) -> ServerSp if value.get("url") or value.get("headers"): raise BindingError(f"MCP server {name}: url and headers belong to an http server") cwd = _resolve(value.get("cwd")) - return ServerSpec(name=name, transport=TRANSPORT_STDIO, command=str(command), - args=tuple(str(_resolve(a)) for a in raw_args), - env=_str_map(name, "env", value.get("env")), cwd=None if cwd is None else str(cwd), + return ServerSpec(name=name, transport=TRANSPORT_STDIO, command=_text(command), + args=tuple(_text(_resolve(a)) for a in raw_args), + env=_str_map(name, "env", value.get("env")), cwd=None if cwd is None else _text(cwd), timeout_ms=timeout_ms) @@ -257,7 +263,7 @@ def _http_server(name: str, value: dict[str, Any], timeout_ms: int) -> ServerSpe raise BindingError(f"MCP server {name}: an http server needs a url") if value.get("command") or value.get("args") or value.get("env") or value.get("cwd"): raise BindingError(f"MCP server {name}: command, args, env and cwd belong to a stdio server") - return ServerSpec(name=name, transport=TRANSPORT_HTTP, url=str(url), + return ServerSpec(name=name, transport=TRANSPORT_HTTP, url=_text(url), headers=_str_map(name, "headers", value.get("headers")), timeout_ms=timeout_ms) @@ -273,7 +279,7 @@ def load_servers(path: str | None = None) -> list[ServerSpec]: if not os.path.isfile(file): raise BindingError(f"MCP server file not found - {file} (mcp.servers names it)") with open(file, encoding="utf-8") as f: - data = yaml.safe_load(f.read()) or {} + data = load_yaml(f.read()) or {} servers = data.get("servers") if isinstance(data, dict) else None if servers is None: servers = {} diff --git a/src/mercury_composable/async_http_request.py b/src/mercury_composable/async_http_request.py index 3585caf..60ea073 100644 --- a/src/mercury_composable/async_http_request.py +++ b/src/mercury_composable/async_http_request.py @@ -30,6 +30,8 @@ async def lookup(headers: dict[str, str], body: Body): from collections.abc import Mapping from typing import Any, NamedTuple +from .config import whole_number + _UNSET: Any = object() @@ -225,14 +227,10 @@ def is_secure(self) -> bool: @property def timeout_seconds(self) -> int | None: - """The entry's timeout in seconds; a caller-sent ``x-ttl`` (milliseconds) wins.""" - ttl = self.header("x-ttl") - if ttl is not None: - try: - return max(1, int(ttl.strip()) // 1000) - except ValueError: - pass - return self._timeout + """The entry's timeout in seconds; a caller-sent ``x-ttl`` (milliseconds) wins when it + is a whole number.""" + ttl = whole_number(self.header("x-ttl")) + return self._timeout if ttl is None else max(1, ttl // 1000) @property def query_string(self) -> str | None: diff --git a/src/mercury_composable/client.py b/src/mercury_composable/client.py index 610d9dc..e0ae5dd 100644 --- a/src/mercury_composable/client.py +++ b/src/mercury_composable/client.py @@ -226,6 +226,11 @@ async def _call(self, route: str, body: Any, headers: dict[str, str] | None, try: return EventEnvelope.from_bytes(payload) except ValueError as e: + # an edge-level REST error - the peer's /api/event sits behind an entry that + # answered for it - is the failure it carries, as the engines' client reads it + failure = _rest_error_reply(payload, response.status) + if failure is not None: + return failure raise AppException(response.status, f"Invalid event-over-http response - {e}") from e @@ -493,24 +498,34 @@ def _decode_frame(name: str | None, text: str, head_seen: bool, return segment, False +def _rest_error_reply(payload: bytes, http_status: int) -> EventEnvelope | None: + """An edge-level REST error arrives as JSON, not as a serialized envelope + ('{"type": "error", "status": n, "message": text}') - unwrap it exactly as + the classic relay does; None when the payload is not one.""" + if http_status < 400: + return None + try: + data = json.loads(payload.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError): + return None + if isinstance(data, dict) and data.get("type") == "error" \ + and isinstance(data.get("message"), str): + return EventEnvelope().set_status(http_status).set_body(data["message"]) + return None + + def _decode_single_shot(payload: bytes, http_status: int) -> EventEnvelope: """Decode a single-shot Event-over-HTTP reply: a serialized envelope normally, with the classic tolerant handling of an edge-level REST error - body ('{"type": "error", "status": n, "message": text}' JSON) and of a - payload that is not a serialized envelope at all.""" + body and of a payload that is not a serialized envelope at all.""" if not payload: return EventEnvelope().set_status(http_status) try: reply = EventEnvelope.from_bytes(payload) except ValueError as e: - if http_status >= 400: - try: - data = json.loads(payload.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError): - data = None - if isinstance(data, dict) and data.get("type") == "error" \ - and isinstance(data.get("message"), str): - return EventEnvelope().set_status(http_status).set_body(data["message"]) + failure = _rest_error_reply(payload, http_status) + if failure is not None: + return failure return EventEnvelope().set_status(400).set_body( f"Invalid event-over-http response - {e}") reply.reply_to = None diff --git a/src/mercury_composable/config.py b/src/mercury_composable/config.py index 643adef..6eb74c0 100644 --- a/src/mercury_composable/config.py +++ b/src/mercury_composable/config.py @@ -18,9 +18,17 @@ behind the Event Script ``f:setConfig`` plugin). :meth:`AppConfig.set` does the same programmatically. - ``${ENV_VAR:default}`` substitution inside values — the environment variable - wins, then a base configuration key of that name, then the default. An - unresolved reference without a default resolves to ``None`` when it is the - whole value (empty string when embedded), matching the engines. + wins, then a configuration key of that name (a ``-D`` override of it before + the file's value, as a key is read), then the default. An unresolved + reference without a default resolves to ``None`` when it is the whole value + (empty string when embedded), and a value its references leave empty is no + value - the key reads as its default - matching the engines. +- A YAML file is read by one rule (:func:`load_yaml`: the core schema of + YAML 1.2.2; the Rust engine reads YAML 1.2 too, the Java engine's reader also + takes the older spellings of YAML 1.1), and a number, a duration and a + switch by one rule (:func:`whole_number`, :func:`duration_ms`, + :func:`switch_value`) - the Node.js twin reads the same file and the same + values the same way. Well-known keys shared with the engines: @@ -34,15 +42,22 @@ from __future__ import annotations +import logging +import math import os import re import sys import threading +from collections.abc import Hashable from typing import Any import yaml _REF = re.compile(r"\$\{([^}]+)}") +# what a key reads as when neither an override nor the file carries it +_MISSING: Any = object() +# by its name, never through the pack's log module: that one reads its settings here +_log = logging.getLogger("mercury.config") DEFAULT_CANDIDATES = [ "resources/application.yml", @@ -52,6 +67,56 @@ RESOURCES_FOLDER = "resources" +# --- how a YAML file is read: the same in both packs ---------------------------------------- +# Every YAML file of a pack - the configuration file, rest.yaml, a companion file - is read by +# YAML 1.2.2: a plain scalar is resolved by the core schema (section 10.3.2 of the specification), +# its rows tried in the order they stand in below, and what none of them matches is text. The +# Node.js twin reads by the same rule, and the Rust engine reads YAML 1.2 as well. PyYAML is the parser here and reads YAML 1.1, as +# the Java engine's reader does, so none of its own rows is kept: yes, no, on and off are text, as +# are a number with an underscore (16_000), in base 2 (0b101) or in base 60 (1:30), a date and the +# lone =; 010 is ten and 0o10 is eight; and << is a key like any other, never the merge key. A +# scalar under an explicit tag is valid when the core schema has the tag and the content is one of +# the tag's rows (section 3.3.3); a document with any other tag does not load. +_TAG = "tag:yaml.org,2002:" +_NULL_TAG, _BOOL_TAG, _INT_TAG, _FLOAT_TAG = f"{_TAG}null", f"{_TAG}bool", f"{_TAG}int", f"{_TAG}float" +_NULL = re.compile(r"(?:~|null|Null|NULL)?\Z") +_BOOL = re.compile(r"(?:true|True|TRUE|false|False|FALSE)\Z") +# \d is the digits 0 to 9 and no other, by flag: Python's own takes the digits of every script +_INT_BASE_10 = re.compile(r"[-+]?\d+\Z", re.ASCII) +_INT_BASE_8 = re.compile(r"0o[0-7]+\Z") +_INT_BASE_16 = re.compile(r"0x[0-9a-fA-F]+\Z") +_EXPONENT = r"(?:[eE][-+]?\d+)?" +_FLOAT_NUMBER = re.compile(rf"[-+]?(?:\.\d+|\d+(?:\.\d*)?){_EXPONENT}\Z", re.ASCII) +_FLOAT_INFINITY = re.compile(r"[-+]?(?:\.inf|\.Inf|\.INF)\Z") +_FLOAT_NAN = re.compile(r"(?:\.nan|\.NaN|\.NAN)\Z") +# the rows in the specification's order, each with the characters a scalar it matches may start +# with (the empty text for no character at all): PyYAML looks a plain scalar up by its first one +_ROWS = ( + (_NULL_TAG, _NULL, ["~", "n", "N", ""]), + (_BOOL_TAG, _BOOL, list("tTfF")), + (_INT_TAG, _INT_BASE_10, list("-+0123456789")), + (_INT_TAG, _INT_BASE_8, ["0"]), + (_INT_TAG, _INT_BASE_16, ["0"]), + (_FLOAT_TAG, _FLOAT_NUMBER, list("-+.0123456789")), + (_FLOAT_TAG, _FLOAT_INFINITY, list("-+.")), + (_FLOAT_TAG, _FLOAT_NAN, ["."]), +) + +# --- how a number, a duration and a switch are read: the same in both packs ----------------- +# the largest whole number both packs hold exactly (2**53 - 1): above it the Node.js twin's +# numbers round, and the twins would read two different numbers from one value +MAX_WHOLE = 9007199254740991 +# the longest delay a timer of the Node.js twin holds, in milliseconds (2**31 - 1, about 24.8 +# days): a setting that sets a timer is refused above it, in both packs +MAX_TIMER_MS = 2147483647 +# the white space ignored around a number: the characters Python's str.strip() and JavaScript's +# trim() both take for white space, so neither pack accepts a character the other refuses +_SPACE = r"[\t-\r \xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]" +# the digits 0 to 9 and no other, by flag: Python's own \d takes the digits of every script +_WHOLE = re.compile(rf"{_SPACE}*(\d+){_SPACE}*", re.ASCII) +_DURATION = re.compile(rf"{_SPACE}*(\d+)(ms|s|m|h|d)?{_SPACE}*", re.ASCII) +_UNIT_MS = {"ms": 1, "s": 1000, "m": 60_000, "h": 3_600_000, "d": 86_400_000} + def main_script_dir() -> str | None: """The folder of the script Python ran (``python app.py``) - where a direct run @@ -61,6 +126,179 @@ def main_script_dir() -> str | None: return os.path.dirname(os.path.abspath(file)) if file else None +def property_text(value: Any) -> str: + """A value as the text a setting reads - what :meth:`AppConfig.get_property` returns, and what + a ``${...}`` reference inside a longer text is replaced by. A boolean is ``true`` or ``false``, + as the Java engine and the Node.js twin write one; anything else is Python's own text, which + for a float is the text the twin writes too (``16000.0``, never ``16000``).""" + if isinstance(value, bool): + return "true" if value else "false" + return str(value) + + +def _integer(text: str) -> int | None: + """The integer a scalar spells in one of the core schema's three forms, else None.""" + if _INT_BASE_10.match(text): + return int(text) + if _INT_BASE_8.match(text): + return int(text, 8) + return int(text, 16) if _INT_BASE_16.match(text) else None + + +def _float(text: str) -> float | None: + """The float a scalar spells in one of the core schema's three forms, else None.""" + if _FLOAT_NUMBER.match(text): + return float(text) + if _FLOAT_INFINITY.match(text): + return -math.inf if text.startswith("-") else math.inf + return math.nan if _FLOAT_NAN.match(text) else None + + +class _Loader(yaml.SafeLoader): + """PyYAML's safe loader with the scalars of YAML 1.2.2's core schema, and a mapping's keys as + text.""" + + def compose_scalar_node(self, anchor: Any) -> yaml.ScalarNode: + """A scalar under the non-specific tag ``!`` is text, whatever its content looks like + (section 10.3.2); PyYAML would resolve it as it resolves a plain scalar.""" + event = self.peek_event() + if isinstance(event, yaml.ScalarEvent) and event.tag == "!": + event.implicit = (False, True) + return super().compose_scalar_node(anchor) + + @staticmethod + def _refusal(node: yaml.ScalarNode, forms: str) -> yaml.YAMLError: + """What a scalar under an explicit tag of the core schema is refused with when its content + is none of the tag's forms; a plain scalar comes here by one of them.""" + return yaml.constructor.ConstructorError( + None, None, f"expected {forms}, but found {node.value!r}", node.start_mark) + + def construct_null(self, node: yaml.ScalarNode) -> None: + if not _NULL.match(self.construct_scalar(node)): + raise self._refusal(node, "nothing, ~ or null") + + def construct_bool(self, node: yaml.ScalarNode) -> bool: + text = self.construct_scalar(node) + if not _BOOL.match(text): + raise self._refusal(node, "true or false") + return text.lower() == "true" + + def construct_int(self, node: yaml.ScalarNode) -> int: + value = _integer(self.construct_scalar(node)) + if value is None: + raise self._refusal(node, "an integer") + return value + + def construct_float(self, node: yaml.ScalarNode) -> float: + value = _float(self.construct_scalar(node)) + if value is None: + raise self._refusal(node, "a float") + return value + + def construct_mapping(self, node: yaml.MappingNode, deep: bool = False) -> dict[Hashable, Any]: + """A mapping under its keys as text: one YAML read as a boolean, a number or null + (``True:``, ``8080:``, ``~:``) is the text of that value. As values, ``True`` and ``1`` + would be one key of a Python mapping; as text they are the two keys that were written. + The key ``<<`` is a key like any other: the core schema has no merge key.""" + if not isinstance(node, yaml.MappingNode): + # a node PyYAML refuses: its own refusal + return super().construct_mapping(node, deep=deep) + mapping: dict[Hashable, Any] = {} + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + if not isinstance(key, Hashable): + # a list or a mapping as a key, refused as PyYAML refuses it + raise yaml.constructor.ConstructorError( + "while constructing a mapping", node.start_mark, + "found unhashable key", key_node.start_mark) + name = "null" if key is None else property_text(key) + mapping[name] = self.construct_object(value_node, deep=deep) + return mapping + + +# tables of its own, so the library's own loaders stay as they are (PyYAML keeps both on the +# class): the rows above and no other resolver, the core schema's tags and no other constructor +_Loader.yaml_implicit_resolvers = { + first: [(tag, pattern) for tag, pattern, firsts in _ROWS if first in firsts] + for first in dict.fromkeys(first for _tag, _pattern, firsts in _ROWS for first in firsts) +} +_Loader.yaml_constructors = { + _NULL_TAG: _Loader.construct_null, + _BOOL_TAG: _Loader.construct_bool, + _INT_TAG: _Loader.construct_int, + _FLOAT_TAG: _Loader.construct_float, + f"{_TAG}str": yaml.SafeLoader.construct_yaml_str, + f"{_TAG}seq": yaml.SafeLoader.construct_yaml_seq, + f"{_TAG}map": yaml.SafeLoader.construct_yaml_map, + None: yaml.SafeLoader.construct_undefined, +} + + +def load_yaml(text: str) -> Any: + """A YAML text as both packs read it - the configuration file, ``rest.yaml``, a companion + file - as plain Python values, a mapping under its keys as text; None for an empty document. + A tab is read as two spaces, as the Java engine reads a file, so one indented with tabs loads + here too.""" + return yaml.load(text.replace("\t", " "), Loader=_Loader) + + +def _number_text(value: Any) -> str | None: + """What a number is read from: a string as written, or the digits of a number with a whole + value - an integer, or a float, which the Node.js twin cannot tell from one. None for + anything else: a boolean, a fraction, a number beyond MAX_WHOLE.""" + if isinstance(value, str): + return value + if isinstance(value, float) and value.is_integer(): + value = int(value) + if isinstance(value, bool) or not isinstance(value, int) or abs(value) > MAX_WHOLE: + return None + return str(value) + + +def _digits(digits: str) -> int | None: + """The whole number a run of ASCII digits spells, or None above MAX_WHOLE - told by the + count of its digits first, so a run of any length is judged without being converted.""" + significant = digits.lstrip("0") + if len(significant) > len(str(MAX_WHOLE)): + return None + number = int(significant or "0") + return number if number <= MAX_WHOLE else None + + +def whole_number(value: Any) -> int | None: + """The whole number a value spells - a number with a whole value, or ASCII digits with white + space around them at most - up to MAX_WHOLE; None when it spells none: a sign, an underscore, + a point or an exponent in text, a digit of another script, a boolean.""" + text = _number_text(value) + match = _WHOLE.fullmatch(text) if text is not None else None + return _digits(match.group(1)) if match else None + + +def duration_ms(value: Any) -> int | None: + """Milliseconds from a whole number of seconds, or from such a number and, right after it, + one of ``ms``, ``s``, ``m``, ``h``, ``d`` - up to MAX_WHOLE milliseconds; None when the value + is neither.""" + text = _number_text(value) + match = _DURATION.fullmatch(text) if text is not None else None + count = _digits(match.group(1)) if match else None + if match is None or count is None: + return None + ms = count * _UNIT_MS[match.group(2) or "s"] + return ms if ms <= MAX_WHOLE else None + + +def switch_value(value: Any, default: bool) -> bool | None: + """What a switch is set to: the boolean, or the text ``true`` or ``false`` in any letter + case; no value and an empty one are the default. None for any other value - it is never read + as off.""" + if value is None or value == "": + return default + if isinstance(value, bool): + return value + lowered = value.lower() if isinstance(value, str) else "" + return lowered == "true" if lowered in ("true", "false") else None + + def _flatten(prefix: str, node: Any, out: dict[str, Any]) -> None: if isinstance(node, dict): for k, v in node.items(): @@ -127,9 +365,10 @@ def _load(self, path: str) -> None: with open(path, "r", encoding="utf-8") as f: text = f.read() if path.endswith((".yml", ".yaml")): - data = yaml.safe_load(text) or {} + data = load_yaml(text) flat: dict[str, Any] = {} - _flatten("", data, flat) + # a document that is not a mapping - an empty file, a list, a lone scalar - has no keys + _flatten("", data if isinstance(data, dict) else {}, flat) self._store = flat else: self._store = _parse_properties(text) @@ -160,22 +399,30 @@ def set(self, key: str, value: Any) -> None: raise ValueError("Config key must not be empty") self._overrides[str(key)] = value + def _stored(self, key: str) -> Any: + """A key's value as it was given - an override first, then the file's; ``_MISSING`` + when neither carries the key, and when the one that does carries no value: a key written + without one (``key:``, a YAML null) reads as a key that is not there, as in the Java + engine, and an override set to None clears the key rather than uncovering the file's.""" + value = self._overrides[key] if key in self._overrides else self._store.get(key) + return _MISSING if value is None else value + def get(self, key: str, default: Any = None) -> Any: - if key in self._overrides: - value = self._overrides[key] - # an override's value resolves references the way a file value does, so a credential - # may be given as -Dkey='${ENV_VAR}' and never appear in the process list - return self._substitute(value, default) if isinstance(value, str) else value - if key in self._store: - value = self._store[key] - if isinstance(value, str): - return self._substitute(value, default) + value = self._stored(key) + if value is _MISSING: + return default + if not isinstance(value, str): return value - return default + # an override's value resolves references the way a file value does, so a credential + # may be given as -Dkey='${ENV_VAR}' and never appear in the process list + resolved = self._substitute(value, default, (key,)) + # a value its references leave empty is no value, as in the Java engine - '${NAME:}' is + # the idiom for an optional setting; an empty text written as one (key: '') stays one + return default if resolved == "" and _REF.search(value) else resolved def get_property(self, key: str, default: str | None = None) -> str | None: value = self.get(key, default) - return None if value is None else str(value) + return None if value is None else property_text(value) def resolve_text(self, value: str) -> Any: """Resolve ``${ENV:default}`` substitution in a text value - the same @@ -183,32 +430,52 @@ def resolve_text(self, value: str) -> Any: app-log-context.yaml).""" return self._substitute(value) + def resolve_property(self, value: str) -> str | None: + """A text value with its references resolved, as text - what :meth:`get_property` + returns for a key that holds it; None when the whole value is a reference that resolves + to nothing (used for ``rest.yaml``, whose values are text).""" + resolved = self._substitute(value) + return None if resolved is None else property_text(resolved) + def exists(self, key: str) -> bool: return key in self._overrides or key in self._store - def _substitute(self, value: str, default: Any = None) -> Any: + def _substitute(self, value: str, default: Any = None, seen: tuple[str, ...] = ()) -> Any: + """``value`` with its references resolved; ``seen`` names the keys being resolved on the + way here, which is how a reference that leads back to one of them is told.""" match = _REF.fullmatch(value.strip()) if match: - resolved = self._resolve_ref(match.group(1)) + resolved = self._resolve_ref(match.group(1), seen) return resolved if resolved is not None else default def repl(m: re.Match[str]) -> str: - replacement = self._resolve_ref(m.group(1)) - return "" if replacement is None else str(replacement) + replacement = self._resolve_ref(m.group(1), seen) + return "" if replacement is None else property_text(replacement) return _REF.sub(repl, value) - def _resolve_ref(self, ref: str) -> Any: + def _resolve_ref(self, ref: str, seen: tuple[str, ...]) -> Any: + """What ``${name:default}`` stands for, in the engine's order: the environment variable, + then the key of that name as a key is read - an override before the file's value - then + the default. A reference that leads back to a key being resolved is a loop: it is logged, + as the engine logs it, and has no value, so its default stands.""" name, sep, fallback = ref.partition(":") name = name.strip() if name in os.environ: return os.environ[name] - if name in self._store and name not in (None, ""): - base = self._store[name] - if isinstance(base, str) and _REF.search(base): - return self._substitute(base) - return base - return fallback if sep else None + default = fallback if sep else None + base = self._stored(name) if name else _MISSING + if base is _MISSING: + return default + if name in seen: + _log.warning("Config loop for '%s' detected", name) + return default + if isinstance(base, str) and _REF.search(base): + resolved = self._substitute(base, None, (*seen, name)) + # a key its own references leave without a value, or empty, is read as a key is: + # it has none, so the default of the reference to it stands + return default if resolved is None or resolved == "" else resolved + return base _lock = threading.Lock() diff --git a/src/mercury_composable/event_stream.py b/src/mercury_composable/event_stream.py index fce65d2..1016a8d 100644 --- a/src/mercury_composable/event_stream.py +++ b/src/mercury_composable/event_stream.py @@ -31,7 +31,7 @@ import base64 from typing import TYPE_CHECKING, Any -from .config import app_config +from .config import MAX_TIMER_MS, app_config, duration_ms from .envelope import EventEnvelope from .exceptions import AppException from .log import get_logger @@ -53,6 +53,8 @@ ENVELOPE = "envelope" X_TTL = "x-ttl" +# the engines' key of the keep-alive comment interval of a Server-Sent Events reply +KEEP_ALIVE = "event.stream.keep.alive" TEXT_EVENT_STREAM = "text/event-stream" STREAM_CALLER_REQUIRED = "Streaming function requires a caller that accepts text/event-stream" @@ -144,21 +146,18 @@ def data_frame(event: EventEnvelope, first_frame: bool) -> bytes: def keep_alive_ms() -> int: """SSE keep-alive comment interval in ms (``event.stream.keep.alive``, - default 30s; 0 disables - the engines' config key).""" - raw = str(app_config().get_property("event.stream.keep.alive", "30s") or "30s") - raw = raw.strip().lower() - if raw in ("0", "0s", "0ms", "0m"): - return 0 - try: - if raw.endswith("ms"): - return int(raw[:-2]) - if raw.endswith("s"): - return int(raw[:-1]) * 1000 - if raw.endswith("m"): - return int(raw[:-1]) * 60_000 - return int(raw) * 1000 - except ValueError: - return 30_000 + default 30s; 0 disables - the engines' config key): a whole number of + seconds, or such a number and, right after it, one of ``ms``, ``s``, + ``m``, ``h``, ``d``, up to the longest delay a timer of the Node.js twin + holds (2147483647 ms). The Java engine reads any other value as no + keep-alive at all, without a word; here it is refused by name - and the + host reads the setting when it starts, so a wrong one stops the start.""" + value = app_config().get(KEEP_ALIVE) + ms = duration_ms("30s" if value is None else value) + if ms is None or ms > MAX_TIMER_MS: + raise AppException(400, f"{KEEP_ALIVE} must be a duration such as 30s, 2m or 500ms" + " (seconds, ms, s, m, h, d), or 0 for none") + return ms class SseParser: diff --git a/src/mercury_composable/log_context.py b/src/mercury_composable/log_context.py index 7845139..121200c 100644 --- a/src/mercury_composable/log_context.py +++ b/src/mercury_composable/log_context.py @@ -14,7 +14,11 @@ in the resources folder (next to application.yml), mapping each output key to a reserved ``$token`` - resolved live per log line - or a constant (a literal, or ``${ENV:default}`` resolved once at load). -- ``app.log.context=false`` opts out. +- ``app.log.context=false`` opts out; the switch is ``true`` or ``false``, and any + other value stops the start by name. +- The template is read as every YAML file of the pack is (YAML 1.2.2's core + schema), and a constant that is not text is the text a setting reads: a + boolean ``true`` or ``false``, a float with its point. - The ``cid`` token is the BUSINESS correlation-id only (the engine-managed my_cid tag); an internal routing id under the ``cid`` label would mislead log aggregation. @@ -29,10 +33,9 @@ import threading from typing import Any -import yaml - -from .config import app_config +from .config import AppConfig, app_config, load_yaml, property_text, switch_value from .envelope import iso_utc +from .exceptions import AppException from .log import get_logger from .trace import RESERVED_CONTEXT_TOKENS, TraceInfo @@ -57,7 +60,7 @@ def default_template() -> dict[str, Any] | None: """The built-in default template from the packaged default-log-context.yaml.""" try: resource = importlib.resources.files("mercury_composable").joinpath(DEFAULT_FILE) - data = yaml.safe_load(resource.read_text(encoding="utf-8")) or {} + data = load_yaml(resource.read_text(encoding="utf-8")) or {} except OSError: return None return _context_section(data) @@ -84,7 +87,10 @@ def __init__(self, template: dict[str, Any] | None): self.tokens: dict[str, str] = {} self.constants: dict[str, Any] = {} for output_key, raw in (template or {}).items(): - self._parse_entry(output_key, raw if isinstance(raw, str) else str(raw)) + # an entry without a value is dropped, as the engines drop it; one that is not text + # is the text a setting reads, the same in both packs + if raw is not None: + self._parse_entry(output_key, raw if isinstance(raw, str) else property_text(raw)) self.enabled = bool(self.tokens or self.constants) def _parse_entry(self, output_key: str, value: str) -> None: @@ -124,12 +130,23 @@ def render(self, info: TraceInfo) -> dict[str, Any]: _instance: LogContextConfig | None = None +def enabled(config: AppConfig) -> bool: + """``app.log.context`` is on unless it says ``false``: the boolean, or the text ``true`` or + ``false`` in any letter case; no value and an empty one are on, the engines' default. The Java + engine reads any other value as on without a word; here it stops the start, by name - the + host reads the switch when it is built.""" + switch = switch_value(config.get(FEATURE_FLAG), True) + if switch is None: + raise AppException(400, f"{FEATURE_FLAG} must be true or false") + return switch + + def _load() -> tuple[LogContextConfig, str | None]: """Resolve the active template; returns (config, warning-or-None). Never logs itself - the caller emits the warning AFTER installing the config, so the log line (which renders through this feature) cannot re-enter.""" config = app_config() - if (config.get_property(FEATURE_FLAG, "true") or "true").lower() == "false": + if not enabled(config): return LogContextConfig(None), None # an application override replaces the default entirely - it sits in the same # resources folder as application.yml (next to the application file, or beside @@ -138,7 +155,7 @@ def _load() -> tuple[LogContextConfig, str | None]: candidate = os.path.join(folder, CONFIG_FILE) if folder else None if candidate and os.path.isfile(candidate): with open(candidate, "r", encoding="utf-8") as f: - section = _context_section(yaml.safe_load(f.read()) or {}) + section = _context_section(load_yaml(f.read()) or {}) if section is None: # the engines log a warning and disable; mirror the outcome return LogContextConfig(None), \ diff --git a/src/mercury_composable/otel/__init__.py b/src/mercury_composable/otel/__init__.py index 682dce5..6958d43 100644 --- a/src/mercury_composable/otel/__init__.py +++ b/src/mercury_composable/otel/__init__.py @@ -17,6 +17,8 @@ from collections.abc import Awaitable, Callable from typing import Any +from ..config import switch_value +from ..exceptions import AppException from ..log import get_logger from ..trace import DISTRIBUTED_TRACE_FORWARDER from .config import FORWARDING_SWITCH, HEADERS, ForwarderSettings, parse_headers @@ -63,9 +65,14 @@ async def forward(_headers: dict[str, str], body: Any) -> None: def enabled(config: Any) -> bool: - """Whether ``otel.forwarding`` is switched on (the text ``true``, case-insensitive).""" - value = config.get_property(FORWARDING_SWITCH) - return value is not None and value.strip().lower() == "true" + """Whether ``otel.forwarding`` is switched on: the boolean, or the text ``true`` or ``false`` + in any letter case; no value and an empty one are off. Any other value was read as off + without a word, which is how forwarding meant to be on stays off - so it stops the start, by + name.""" + switch = switch_value(config.get(FORWARDING_SWITCH), False) + if switch is None: + raise AppException(400, f"{FORWARDING_SWITCH} must be true or false") + return switch def activate(config: Any, registry: Any) -> Exporter | None: @@ -73,7 +80,8 @@ def activate(config: Any, registry: Any) -> Exporter | None: ``otel.forwarding=true`` - the host's start-up hook. Returns the exporter (so the host can close it at shutdown), or ``None`` when forwarding is off or a function already occupies the route (an application's own forwarder - wins, as in the engines). A misconfigured endpoint fails the start.""" + wins, as in the engines). A misconfigured endpoint fails the start, and so does a switch + that is neither true nor false.""" if not enabled(config): return None if registry.exists(DISTRIBUTED_TRACE_FORWARDER): diff --git a/src/mercury_composable/otel/export.py b/src/mercury_composable/otel/export.py index 2e4a289..8fd318e 100644 --- a/src/mercury_composable/otel/export.py +++ b/src/mercury_composable/otel/export.py @@ -139,8 +139,9 @@ async def _attempt(self, body: bytes) -> None: async with self._client().post(self.endpoint, data=body, headers=headers) as response: payload = await response.read() status = response.status - except (TimeoutError, aiohttp.ClientError, OSError) as e: - # the transport failed before an HTTP answer - retried like the Java + except (aiohttp.ClientError, OSError) as e: + # the transport failed before an HTTP answer - a timeout among the + # failures, since TimeoutError is an OSError - retried like the Java # exporter retries every IOException raise _AttemptError(True, str(e) or e.__class__.__name__) from None _classify(status, payload) diff --git a/src/mercury_composable/rest_automation.py b/src/mercury_composable/rest_automation.py index 4fd63cb..1ba78ad 100644 --- a/src/mercury_composable/rest_automation.py +++ b/src/mercury_composable/rest_automation.py @@ -46,13 +46,12 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any -import yaml -from aiohttp import BodyPartReader, MultipartReader, web +from aiohttp import web from .actuator import app_origin from .async_http_request import AsyncHttpRequest, UploadedFile from .bus import DeliveryTimeout, EventBus, round_trip_record -from .config import AppConfig +from .config import AppConfig, load_yaml, switch_value, whole_number from .envelope import EventEnvelope, iso_utc from .event_stream import ( DATA, @@ -83,6 +82,7 @@ parse_body, parse_cookies, parse_query, + parse_upload, pretty_json, stream_text, substitute_values, @@ -109,15 +109,16 @@ UPLOAD_MAX_BYTES = "rest.upload.max.bytes" DEFAULT_UPLOAD_MAX_BYTES = 16 * 1024 * 1024 MULTIPART_FORM_DATA = "multipart/form-data" +# what an upload's body may take on the wire beyond the parts' contents - its delimiters and the +# parts' headers - before it is refused unread +MULTIPART_HEADROOM = 1024 * 1024 # the host's limit on a request body it reads into memory - the web application's client_max_size MAX_BODY_BYTES = 16 * 1024 * 1024 -# an upload's parts are text fields and files: the refusal of a part that is multipart itself -NESTED_PART = "Upload takes text fields and files, not a nested multipart part" -# the answer when a reply cannot be rendered, and what the serializer raises for a body it refuses: -# a type JSON does not hold, a structure that contains itself or runs too deep, text that is not -# Unicode +# the answer when a reply cannot be rendered, and what a serializer raises for a body it refuses: +# a type JSON or the wire codec does not hold, a structure that contains itself or runs too deep, +# text that is not Unicode UNRENDERABLE = "Reply cannot be rendered" -_SERIALIZER_ERRORS = (TypeError, ValueError, RecursionError) +SERIALIZER_ERRORS = (TypeError, ValueError, RecursionError) # the edge's own service name in the trace records (the engines' REST edge) HTTP_REQUEST = "http.request" EVENT_API_SERVICE = "event.api.service" @@ -134,9 +135,13 @@ def enabled(config: AppConfig) -> bool: - """``rest.automation`` is on - a boolean or the text ``true``.""" - value = config.get(REST_AUTOMATION, False) - return value is True or (isinstance(value, str) and value.strip().lower() == "true") + """``rest.automation`` is on: the boolean, or the text ``true`` or ``false`` in any letter + case; no value and an empty one are off. The Java engine reads any other value as off without + a word, which is how a switch meant to be on stays off - so here it stops the start, by name.""" + switch = switch_value(config.get(REST_AUTOMATION), False) + if switch is None: + raise AppException(400, f"{REST_AUTOMATION} must be true or false") + return switch def resolve_location(config: AppConfig, location: str) -> str | None: @@ -174,12 +179,12 @@ def load_table(config: AppConfig) -> RoutingTable: location) else: with open(path, "r", encoding="utf-8") as f: - data = yaml.safe_load(f.read()) + data = load_yaml(f.read()) if data is None: log.warning("REST automation configuration is empty - %s (the default endpoints only)", path) else: - table = RoutingTable.load(substitute_values(data, config.resolve_text)) + table = RoutingTable.load(substitute_values(data, config.resolve_property)) log.info("Loading REST automation from %s", path) table.merge_defaults() return table @@ -202,7 +207,7 @@ def body_too_large() -> AppException: return AppException(413, f"Request body exceeds {MAX_BODY_BYTES} bytes") -def _unrendered(service: str | None, cause: Exception) -> AppException: +def unrendered(service: str | None, cause: Exception) -> AppException: """The failure of a reply that cannot be rendered - a body the serializer refuses. The reason goes to the log; the response and the trace record carry the one message both packs answer.""" log.error("Unable to render the reply of %s - %s", service or "unknown", cause) @@ -253,16 +258,6 @@ async def _prepare_headers(self) -> None: self._headers.popall("Content-Type", None) -class _NestedPart(MultipartReader): - """A part of an upload that is multipart itself - a ``multipart/*`` content type - as aiohttp - hands it over when told not to open it. An upload refuses such a part, so it is only told - apart from a field or a file: nothing of it is read, not even its boundary.""" - - def __init__(self, *_args: Any, **_limits: Any) -> None: - # nothing to set up: the part is never read - pass - - class _RestEdge: """The trace records of one traced call through a REST entry - what the engines leave: the edge's ``http.request`` round trip (the SERVER span, parented onto the caller's span from the @@ -328,10 +323,13 @@ def __init__(self, table: RoutingTable, config: AppConfig, server: EventApiServe or DEFAULT_CORRELATION_ID_HEADER).lower() self.traceparent_header = (config.get_property(TRACEPARENT_HEADER, TRACEPARENT) or TRACEPARENT).lower() - try: - self.upload_max_bytes = int(config.get(UPLOAD_MAX_BYTES, DEFAULT_UPLOAD_MAX_BYTES)) - except (TypeError, ValueError): - self.upload_max_bytes = DEFAULT_UPLOAD_MAX_BYTES + # a bound that is no whole number stops the start: a default taken in its place would + # be a bound the installation did not set + bound = config.get(UPLOAD_MAX_BYTES) + limit = whole_number(DEFAULT_UPLOAD_MAX_BYTES if bound is None else bound) + if limit is None: + raise AppException(400, f"{UPLOAD_MAX_BYTES} must be a whole number >= 0") + self.upload_max_bytes = limit self._fallback: list[web.AbstractRoute] = [] self._started = False @@ -436,7 +434,16 @@ async def _prepare(self, request: web.Request, assigned: AssignedRoute) -> _Prep query = parse_query(query_text) cookies = parse_cookies(headers.pop("cookie", None)) accept = headers.get("accept") - parsed, files = await self._read_body(request, info, method, query, headers) + trace_path = f"{method} {path}?{query_text}" if query_text else f"{method} {path}" + edge = _RestEdge(self.bus, trace_id, trace_path, parent_span) if trace_id else None + try: + parsed, files = await self._read_body(request, info, method, query, headers) + except AppException as e: + # the engines' edge: a traced request is recorded once its trace is resolved, so a + # refusal raised while the body is read - a 400, a 413 - leaves its record + if edge is not None: + edge.record(e.status, e.message) + raise http_request = (AsyncHttpRequest().set_method(method).set_url(path) .set_remote_ip(request.remote or "unknown") .set_secure(headers.get("x-forwarded-proto") == "https") @@ -453,8 +460,6 @@ async def _prepare(self, request: web.Request, assigned: AssignedRoute) -> _Prep http_request.set_query_string(query_text) for name, value in cookies.items(): http_request.set_cookie(name, value) - trace_path = f"{method} {path}?{query_text}" if query_text else f"{method} {path}" - edge = _RestEdge(self.bus, trace_id, trace_path, parent_span) if trace_id else None return _Prepared(http_request, cid, cid_header, trace_id, trace_path, accept, edge, method == "HEAD") @@ -519,60 +524,24 @@ def _set_body(http_request: AsyncHttpRequest, parsed: ParsedBody, http_request.set_body(None if parsed.kind == "form" else parsed.value) async def _read_multipart(self, request: web.Request) -> tuple[list[UploadedFile], dict[str, str]]: - """The parts of a multipart body: a part with a filename is a file (its field name the - upload tag, its declared type or octet-stream), any other part a text field; a part that - is multipart itself is refused. The parts together, counted in bytes as they arrive, may - not exceed ``rest.upload.max.bytes`` - a 413 the moment they do.""" - files: list[UploadedFile] = [] - fields: dict[str, str] = {} - total = 0 - try: - reader = await request.multipart() - # a part that is multipart itself is handed over as a marker, never opened - reader.multipart_reader_cls = _NestedPart - while True: - # reader.next() rather than an async for: the iteration protocol is not typed on - # every Python the pack supports - part = await reader.next() - if part is None: - break - if not isinstance(part, BodyPartReader): - raise AppException(400, NESTED_PART) - if part.filename: - content, total = await self._read_file(part, total) - content_type = part.headers.get("Content-Type", "application/octet-stream") - files.append(UploadedFile(part.filename, content_type, len(content), - part.name or "file", content)) - else: - text, total = await self._read_field(part, total) - fields[part.name or ""] = text - except AppException: - raise - except (ValueError, LookupError, AssertionError) as e: - raise AppException(400, f"Invalid multipart body - {e}") from None - return files, fields - - async def _read_file(self, part: BodyPartReader, total: int) -> tuple[bytes, int]: - """A part's bytes - a file's, or a text field's before it is decoded - read in chunks so - the bound holds while they arrive; ``total`` is the size of the upload before this part - and comes back with it counted.""" + """The parts of a multipart body, read by the pack's own reader (``parse_upload``): a + part with a filename is a file (its field name the upload tag, its declared type or + octet-stream), any other part a text field; what a form does not send is refused by name. + The parts together, counted in bytes as they arrived, may not exceed + ``rest.upload.max.bytes`` - a 413; a body that outgrows the bound by more than its framing + can take is refused while it arrives, the rest of it unread.""" + bound = self.upload_max_bytes chunks: list[bytes] = [] + size = 0 while True: - chunk = await part.read_chunk(65536) + chunk = await request.content.read(65536) if not chunk: break - total += len(chunk) - if total > self.upload_max_bytes: - raise AppException(413, f"Upload exceeds {self.upload_max_bytes} bytes") + size += len(chunk) + if size > bound + MULTIPART_HEADROOM: + raise AppException(413, f"Upload exceeds {bound} bytes") chunks.append(chunk) - return b"".join(chunks), total - - async def _read_field(self, part: BodyPartReader, total: int) -> tuple[str, int]: - """A text field of the form, counted against the same bound as the files: the bytes that - arrive, never the length of the text they spell. The text is what aiohttp's ``part.text()`` - reads - the part's transfer encoding undone, then its charset.""" - data, total = await self._read_file(part, total) - return bytes(part.decode(data)).decode(part.get_charset(default="utf-8")), total + return parse_upload(b"".join(chunks), request.headers.get("Content-Type"), bound) @staticmethod def _event(to: str, prepared: _Prepared) -> EventEnvelope: @@ -695,8 +664,8 @@ def _respond(info: RouteInfo, prepared: _Prepared, reply: EventEnvelope) -> web. body=reply.body, accept=prepared.accept, is_head=prepared.is_head, transform=info.headers.response if info.headers else None, cors=info.cors, cid=prepared.cid, cid_header=prepared.cid_header) - except _SERIALIZER_ERRORS as e: - raise _unrendered(info.service, e) from None + except SERIALIZER_ERRORS as e: + raise unrendered(info.service, e) from None response = _RestResponse(status=mapped.status, body=mapped.body) response.headers.popall("Content-Type", None) for name, value in mapped.headers: @@ -755,10 +724,9 @@ def _stream_head(first: EventEnvelope, if key in (X_EVENT_STREAM, X_EVENT_NAME, "x-stream-id"): continue if key == X_TTL: - with contextlib.suppress(ValueError): - seconds = int(value.strip()) - if seconds > 0: - idle_ms = seconds * 1000 + seconds = whole_number(value) + if seconds: + idle_ms = seconds * 1000 elif key == "content-type": content_type = value.lower() elif key == "set-cookie": @@ -805,8 +773,8 @@ async def _render(self, response: web.StreamResponse, queue: asyncio.Queue[Event return head_status, None else: return await self._write_failure(response, event, sse) - except _SERIALIZER_ERRORS as e: - return await self._write_unrendered(response, sse, _unrendered(event.sender, e)) + except SERIALIZER_ERRORS as e: + return await self._write_unrendered(response, sse, unrendered(event.sender, e)) async def _next_marked(self, response: web.StreamResponse, queue: asyncio.Queue[EventEnvelope], idle_ms: int, ping_ms: int) -> tuple[EventEnvelope, str] | None: @@ -919,11 +887,9 @@ async def _builtin(self, request: web.Request, assigned: AssignedRoute) -> web.S await self._authenticate(info, prepared) except AppException as e: return _error(e.status, e.message) - ttl_ms = info.timeout_ms - header = request.headers.get(X_TTL) - if header is not None: - with contextlib.suppress(ValueError): - ttl_ms = max(1000, int(header.strip())) + # a caller's x-ttl that is a whole number wins over the entry's timeout + sent = whole_number(request.headers.get(X_TTL)) + ttl_ms = info.timeout_ms if sent is None else max(1000, sent) try: response = await asyncio.wait_for(self._builtin_call(request, info.service), ttl_ms / 1000) except TimeoutError: @@ -989,7 +955,13 @@ async def _apply_filter(self, request: web.Request, path: str, filtered = await self._run_filter(request, service, path) filter_headers = list(filtered.headers.items()) if filtered.get_status() != 200: - kind, payload = envelope_payload(filtered) + try: + kind, payload = envelope_payload(filtered) + except SERIALIZER_ERRORS as e: + # the filter's own reply is the response, and it cannot be rendered: the + # answer any other such reply gets + failure = unrendered(route, e) + return filter_headers, _error(failure.status, failure.message) response = web.Response(status=filtered.get_status(), body=payload) response.headers.popall("Content-Type", None) for name, value in filter_headers: diff --git a/src/mercury_composable/rest_routing.py b/src/mercury_composable/rest_routing.py index 6b5d8f0..004e376 100644 --- a/src/mercury_composable/rest_routing.py +++ b/src/mercury_composable/rest_routing.py @@ -16,26 +16,31 @@ (``flow:`` or ``service: http.flow.adapter`` - flows run in the engines), the HTTP relay (an ``http(s)://`` service) and the A/B dual service (a list of two routes). ``upload: true`` is the pack's bounded form of the engines' streaming upload: the files arrive in the request map, their -bytes beside the engines' keys, within ``rest.upload.max.bytes``. Deferred as in the Rust port: -``custom.content.types``, ``mime.types``, XML and request-body streaming. +bytes beside the engines' keys, within ``rest.upload.max.bytes`` - the multipart body is read by +:func:`parse_upload`, the pack's own reader, so both packs take the same parts and refuse the +same ones. Deferred as in the Rust port: ``custom.content.types``, ``mime.types``, XML and +request-body streaming. """ from __future__ import annotations import json +import re from collections.abc import Callable, Mapping from dataclasses import dataclass, field from typing import Any, NamedTuple from urllib.parse import unquote_plus -import yaml - +from .async_http_request import UploadedFile +from .config import duration_ms, load_yaml, property_text, switch_value from .exceptions import AppException ALLOWED_METHODS = ("GET", "PUT", "POST", "DELETE", "HEAD", "PATCH") DEFAULT_TIMEOUT_MS = 30_000 MIN_TIMEOUT_MS = 1_000 MAX_TIMEOUT_MS = 300_000 +# what an entry's timeout is, in the words of its refusal +TIMEOUT_RULE = "a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" FLOW_ADAPTER = "http.flow.adapter" # the engines' built-in default endpoints (platform-core's default-rest.yaml): merged only when the # application's rest.yaml does not already claim the URL - a user entry always wins @@ -75,38 +80,46 @@ _APPLICATION_XML = "application/xml" _TEXT_HTML = "text/html" _TEXT_PLAIN = "text/plain" +_OCTET_STREAM = "application/octet-stream" HTML_START = "
\n"
 HTML_END = "\n
" +# ---- an upload's multipart body: what a browser's form sends, and the refusal of anything else ---- +# an upload's parts are text fields and files: the refusal of a part that is multipart itself +NESTED_PART = "Upload takes text fields and files, not a nested multipart part" +# a boundary as RFC 2046 allows one: up to 70 of these characters, the last one not a space +_BOUNDARY = re.compile(r"[0-9A-Za-z'()+_,\-./:=? ]{0,69}[0-9A-Za-z'()+_,\-./:=?]") +# one parameter of a header - ; name="value" or ; name=value, no blank inside the name or beside +# the equals sign - and what may follow the last one +_PARAMETER = re.compile(r'[ \t]*;[ \t]*([^=;" \t]*)=(?:"([^"]*)"|([^;"]*))') +_PARAMETERS_END = re.compile(r"[ \t]*(?:;[ \t]*)?") +# the three characters a form escapes in a field name and a filename +_ESCAPED = re.compile(r"%(22|0[AaDd])") +_UNESCAPED = {"22": '"', "0a": "\n", "0d": "\r"} +# the charsets the extended form of a parameter may name (RFC 5987: name*, filename*): its codec, +# and its name in a refusal; and a run of the percent-encoded bytes of its value +_EXTENDED_CHARSETS = {"utf-8": ("utf-8", "UTF-8"), "iso-8859-1": ("latin-1", "ISO-8859-1")} +_PERCENT_BYTES = re.compile(r"(?:%[0-9A-Fa-f]{2})+") +# the transfer encodings that leave a part's bytes as they are +_PLAIN_TRANSFER = ("7bit", "8bit", "binary") +# the charsets a text field may declare: its codec, and its name in a refusal +_FIELD_CHARSETS = {"utf-8": ("utf-8", "UTF-8"), "utf8": ("utf-8", "UTF-8"), + "iso-8859-1": ("latin-1", "ISO-8859-1"), "us-ascii": ("ascii", "US-ASCII")} def _text(value: Any) -> str | None: return value if isinstance(value, str) else None -def parse_timeout(value: Any) -> int: - """A duration like ``30s``, ``2m``, ``1500ms`` or a bare number of seconds, in milliseconds; - the default 30 s when unparsable, clamped to 1 s - 5 min (the engines' rule).""" - parsed: int | None = None - if isinstance(value, bool): - parsed = None - elif isinstance(value, (int, float)): - parsed = int(value) * 1000 - elif isinstance(value, str): - text = value.strip().lower() - try: - if text.endswith("ms"): - parsed = int(text[:-2].strip()) - elif text.endswith("m"): - parsed = int(text[:-1].strip()) * 60_000 - elif text.endswith("s"): - parsed = int(text[:-1].strip()) * 1000 - else: - parsed = int(text) * 1000 - except ValueError: - parsed = None - if parsed is None or parsed < 0: - parsed = DEFAULT_TIMEOUT_MS - return max(MIN_TIMEOUT_MS, min(MAX_TIMEOUT_MS, parsed)) +def parse_timeout(value: Any) -> int | None: + """An entry's ``timeout`` in milliseconds: a whole number of seconds, or such a number and, + right after it, one of ``ms``, ``s``, ``m``, ``h``, ``d`` (``30s``, ``2m``, ``1500ms``), + clamped to 1 s - 5 min as the engines clamp it; no value is the default 30 s. None for a + value that is no duration: the Java engine reads one as a second without a word, so here the + entry is refused.""" + if value is None: + return DEFAULT_TIMEOUT_MS + ms = duration_ms(value) + return None if ms is None else max(MIN_TIMEOUT_MS, min(MAX_TIMEOUT_MS, ms)) @dataclass @@ -435,19 +448,17 @@ def _parse_flag(index: int, entry: Mapping[str, Any], key: str) -> bool: ``${NAME:default}`` reference resolves to; ``false``, no value and an empty one leave it off. The engine reads any other value as off without a word, which is how a flag meant to be on stays off - so here it fails the load, by the entry and the flag.""" - value = _lookup(entry, key) - if value is None or value == "": - return False - if isinstance(value, bool): - return value - lowered = value.lower() if isinstance(value, str) else "" - if lowered in ("true", "false"): - return lowered == "true" - raise AppException(400, f"rest[{index}] '{key}' must be true or false") + switch = switch_value(_lookup(entry, key), False) + if switch is None: + raise AppException(400, f"rest[{index}] '{key}' must be true or false") + return switch def _parse_route(index: int, entry: Mapping[str, Any], cors_blocks: Mapping[str, CorsInfo], header_blocks: Mapping[str, HeaderInfo]) -> RouteInfo: + """One ``rest`` entry. Its faults are reported in this order, the first one found failing the + load: the service, the url, the methods, then the cors and the headers reference, then the + timeout, then the flags - tracing, stream, upload.""" service = _parse_service(index, entry) url = _text(_lookup(entry, "url")) if url is None: @@ -465,9 +476,12 @@ def _parse_route(index: int, entry: Mapping[str, Any], cors_blocks: Mapping[str, headers = header_blocks.get(headers_id) if headers is None: raise AppException(400, f"rest[{index}] unknown headers id '{headers_id}'") + timeout_ms = parse_timeout(_lookup(entry, "timeout")) + if timeout_ms is None: + raise AppException(400, f"rest[{index}] 'timeout' must be {TIMEOUT_RULE}") return RouteInfo( service=service, methods=methods, url=url, - timeout_ms=parse_timeout(_lookup(entry, "timeout")), + timeout_ms=timeout_ms, cors=cors, headers=headers, authentication=_text(_lookup(entry, "authentication")), tracing=_parse_flag(index, entry, "tracing"), @@ -487,7 +501,7 @@ def substitute_values(data: Any, resolve: Callable[[str], Any]) -> Any: resolved = resolve(data) if resolved is None: return data - return resolved if isinstance(resolved, str) else str(resolved) + return resolved if isinstance(resolved, str) else property_text(resolved) if isinstance(data, list): return [substitute_values(item, resolve) for item in data] if isinstance(data, Mapping): @@ -522,7 +536,7 @@ def load(cls, data: Any) -> RoutingTable: @classmethod def from_yaml_text(cls, text: str) -> RoutingTable: - return cls.load(yaml.safe_load(text)) + return cls.load(load_yaml(text)) def has_url(self, url: str) -> bool: return any(route.url.lower() == url.lower() for route in self.routes) @@ -664,6 +678,207 @@ def parse_body(content_type: str | None, data: bytes) -> ParsedBody: return ParsedBody("bytes", bytes(data)) +def _invalid_upload(reason: str) -> AppException: + return AppException(400, f"Invalid multipart body - {reason}") + + +def _parameters(text: str) -> dict[str, str] | None: + """The parameters of a header after its first value - ``; name="a"; filename=b`` - under + their names in lower case, the first of a name standing: a value in double quotes runs to the + next one, a bare value to the next semicolon. None when the text is anything else.""" + found: dict[str, str] = {} + at = 0 + while True: + match = _PARAMETER.match(text, at) + if match is None: + break + quoted = match.group(2) + value = quoted if quoted is not None else match.group(3).strip(" \t") + found.setdefault(match.group(1).lower(), value) + at = match.end() + return found if _PARAMETERS_END.fullmatch(text, at) else None + + +def _header_parameters(headers: Mapping[str, str], name: str) -> tuple[str, dict[str, str]]: + """A part's header as its first value, in lower case, and its parameters; a header the part + does not carry is an empty value without parameters.""" + first, sep, rest = headers.get(name, "").partition(";") + parameters = _parameters(sep + rest) + if parameters is None: + raise _invalid_upload("a part's header parameters are malformed") + return first.strip(" \t").lower(), parameters + + +def _boundary(content_type: str | None) -> bytes: + """The boundary the request's content type declares, as the bytes the body is delimited by.""" + _, sep, rest = (content_type or "").partition(";") + boundary = (_parameters(sep + rest) or {}).get("boundary", "") + if not _BOUNDARY.fullmatch(boundary): + raise _invalid_upload("the content type declares no boundary") + return boundary.encode("ascii") + + +def _first_delimiter(body: bytes, delimiter: bytes) -> int: + """Where the first delimiter starts: at the first byte, or on a line of its own after a + preamble, which is ignored.""" + if body.startswith(delimiter): + return 0 + at = body.find(b"\r\n" + delimiter) + if at == -1: + raise _invalid_upload("no part is delimited by the boundary the content type declares") + return at + 2 + + +def _after_delimiter(body: bytes, at: int) -> int: + """Where the part after a delimiter starts - past blanks and the line end - or -1 when the + delimiter is the closing one, with two dashes after it; what follows that is ignored.""" + if body[at:at + 2] == b"--": + return -1 + while body[at:at + 1] in (b" ", b"\t"): + at += 1 + if body[at:at + 2] != b"\r\n": + raise _invalid_upload("a delimiter is followed by neither a line end nor the closing dashes") + return at + 2 + + +def _part_headers(body: bytes, at: int) -> tuple[dict[str, str], int]: + """A part's header lines under their names in lower case, the first of a name standing, and + where its content starts - after the empty line.""" + headers: dict[str, str] = {} + while True: + end = body.find(b"\r\n", at) + if end == -1: + raise _invalid_upload("the closing delimiter is missing") + if end == at: + return headers, end + 2 + try: + line = body[at:end].decode("utf-8") + except UnicodeDecodeError: + raise _invalid_upload("a part's headers are not UTF-8") from None + name, sep, value = line.partition(":") + if not sep: + raise _invalid_upload("a part's header line is not 'name: value'") + headers.setdefault(name.strip(" \t").lower(), value.strip(" \t")) + at = end + 2 + + +def _unescape(text: str) -> str: + """A field name or a filename as the form spelt it: a double quote, a line feed and a carriage + return arrive as ``%22``, ``%0A`` and ``%0D``.""" + return _ESCAPED.sub(lambda match: _UNESCAPED[match.group(1).lower()], text) + + +def _extended(key: str, value: str) -> str: + """A parameter in the extended form of RFC 5987 (``name*``, ``filename*``) as text - what a + client writes for a name that is not ASCII: ``charset'language'value``, the charset UTF-8 or + ISO-8859-1 in any letter case, the language passed over, and the value's bytes + percent-encoded, any other character standing for itself.""" + charset, first, rest = value.partition("'") + _language, second, encoded = rest.partition("'") + if not (first and second): + raise _invalid_upload(f"a part's {key} is not charset'language'value") + codec = _EXTENDED_CHARSETS.get(charset.lower()) + if codec is None: + raise AppException(400, f"Upload takes a part's {key} in UTF-8 or ISO-8859-1, not in '{charset}'") + if "%" in _PERCENT_BYTES.sub("", encoded): + raise _invalid_upload(f"a part's {key} holds a % that two hexadecimal digits do not follow") + try: + return _PERCENT_BYTES.sub( + lambda match: bytes.fromhex(match.group().replace("%", "")).decode(codec[0]), encoded) + except UnicodeDecodeError: + raise AppException(400, f"Upload parameter {key} of a part is not {codec[1]}") from None + + +def _named(parameters: Mapping[str, str], key: str) -> str | None: + """A part's ``name`` or ``filename``: the extended parameter when the part carries one - it + wins over the plain one, wherever it stands - else the plain one as the form spelt it; None + when the part carries neither.""" + extended = parameters.get(f"{key}*") + if extended is not None: + return _extended(f"{key}*", extended) + plain = parameters.get(key) + return None if plain is None else _unescape(plain) + + +def _part_names(headers: Mapping[str, str]) -> tuple[str, str | None]: + """A part's field name and, for a file, its filename - after the part is held against what an + upload takes: no part that is multipart itself, a ``form-data`` disposition with a ``name``, + and bytes that arrive as they are.""" + declared = (base_content_type(headers.get("content-type")) or "").lower() + if declared == "multipart" or declared.startswith("multipart/"): + raise AppException(400, NESTED_PART) + disposition, parameters = _header_parameters(headers, "content-disposition") + name = _named(parameters, "name") + if disposition != "form-data" or name is None: + raise _invalid_upload("a part is not 'Content-Disposition: form-data' with a name") + transfer = headers.get("content-transfer-encoding") + if transfer is not None and transfer.lower() not in _PLAIN_TRANSFER: + raise AppException(400, "Upload takes the bytes of a part as they are, not a" + f" Content-Transfer-Encoding of '{transfer}'") + encoding = headers.get("content-encoding") + if encoding is not None and encoding.lower() != "identity": + raise AppException( + 400, f"Upload takes the bytes of a part as they are, not a Content-Encoding of '{encoding}'") + return name, _named(parameters, "filename") + + +def _field_text(name: str, headers: Mapping[str, str], content: bytes) -> str: + """A text field's bytes as text: UTF-8, unless the part declares ISO-8859-1 or US-ASCII.""" + _, parameters = _header_parameters(headers, "content-type") + declared = parameters.get("charset", "utf-8") + charset = _FIELD_CHARSETS.get(declared.lower()) + if charset is None: + raise AppException( + 400, f"Upload takes a text field in UTF-8, ISO-8859-1 or US-ASCII, not in '{declared}'") + try: + return content.decode(charset[0]) + except UnicodeDecodeError: + raise AppException(400, f"Upload text field '{name}' is not {charset[1]}") from None + + +def parse_upload(body: bytes, content_type: str | None, + bound: int) -> tuple[list[UploadedFile], dict[str, str]]: + """The files and the text fields of a ``multipart/form-data`` body, read as a browser's form + sends one and the same way in both packs. The body is delimited by the boundary its content + type declares, with ``\\r\\n`` line ends; a part is ``Content-Disposition: form-data`` with a + ``name`` and, for a file, a ``filename`` (an empty one included: a file input left empty) - + in quotes, where ``%22``, ``%0A`` and ``%0D`` stand for a quote and the two line ends, or bare, + or in the extended form a client writes for a name that is not ASCII (``filename*=UTF-8''...``, + ``name*``), which wins over the plain one. + A file's type is its ``Content-Type`` as written, ``application/octet-stream`` without one; + its bytes are the bytes that arrived. A text field is UTF-8, or the ISO-8859-1 or US-ASCII its + part declares; a later field of a name replaces an earlier one. The parts' contents together, + counted in bytes in the order they arrive, may not exceed ``bound`` - a 413. Anything else is + a 400 that names it: a part that is multipart itself, a part without a name, an extended + parameter that is malformed, in another charset or not the text it declares, a transfer or + content encoding that changes the bytes, a field in another charset or one that is not the + text it declares, a body that is not delimited as declared.""" + delimiter = b"--" + _boundary(content_type) + files: list[UploadedFile] = [] + fields: dict[str, str] = {} + total = 0 + at = _first_delimiter(body, delimiter) + while True: + at = _after_delimiter(body, at + len(delimiter)) + if at == -1: + return files, fields + headers, at = _part_headers(body, at) + name, filename = _part_names(headers) + end = body.find(b"\r\n" + delimiter, at) + if end == -1: + raise _invalid_upload("the closing delimiter is missing") + content = body[at:end] + total += len(content) + if total > bound: + raise AppException(413, f"Upload exceeds {bound} bytes") + if filename is None: + fields[name] = _field_text(name, headers, content) + else: + files.append(UploadedFile(filename, headers.get("content-type") or _OCTET_STREAM, + len(content), name or "file", content)) + at = end + 2 + + def accept_fallback_type(accept: str | None) -> str | None: """The response content type when the function set none: ``text/html`` for a browser, ``application/json`` for json, ``*/*`` and xml (the port's XML deferral), no ``Accept`` means no diff --git a/src/mercury_composable/server.py b/src/mercury_composable/server.py index e339ac3..1d0e91e 100644 --- a/src/mercury_composable/server.py +++ b/src/mercury_composable/server.py @@ -46,10 +46,10 @@ from aiohttp import web -from . import otel +from . import log_context, otel from .actuator import Actuator, app_origin from .bus import DeliveryTimeout, EventBus, round_trip_record -from .config import app_config +from .config import AppConfig, app_config, whole_number from .envelope import EventEnvelope, iso_utc from .event_stream import ( DATA, @@ -61,9 +61,16 @@ keep_alive_ms, stream_signal, ) +from .exceptions import AppException from .log import get_logger from .registry import FunctionRegistry, ServiceDef, default_registry -from .rest_automation import MAX_BODY_BYTES, RestAutomation, body_too_large +from .rest_automation import ( + MAX_BODY_BYTES, + SERIALIZER_ERRORS, + RestAutomation, + body_too_large, + unrendered, +) from .static_content import StaticContent, resolve_folder from .trace import MY_CID_TAG, MY_CORRELATION_ID @@ -73,6 +80,8 @@ X_EVENT_API = "x-event-api" # the engines' reserved route name for the Event-over-HTTP ingress EVENT_API_SERVICE = "event.api.service" +SERVER_PORT = "rest.server.port" +DEFAULT_PORT = 8085 # the edge's own service name and path in its round-trip record (the engines' REST edge) HTTP_REQUEST = "http.request" EDGE_PATH = "POST /api/event" @@ -88,13 +97,34 @@ def _transport_error(status: int, message: str) -> web.Response: return web.Response(status=status, body=reply.to_bytes(), content_type=OCTET_STREAM) -def _ttl(request: web.Request) -> int: - """The ``x-ttl`` header in milliseconds, floor 1000 - the bound on the handler's execution.""" +def _relay(route: str | None, reply: EventEnvelope) -> tuple[web.Response, int, str | None]: + """A single-shot reply as the HTTP 200 that carries its envelope, with the status and the + error for the edge's record. A reply the wire codec refuses - a type MsgPack does not hold - is + answered as any other reply that cannot be rendered: a 500, here an envelope as every + transport failure of this endpoint is.""" try: - ttl = int(request.headers.get(X_TTL, "0") or 0) - except ValueError: - ttl = 0 - return max(1000, ttl) + body = reply.to_bytes() + except SERIALIZER_ERRORS as e: + failure = unrendered(route, e) + return _transport_error(failure.status, failure.message), failure.status, failure.message + return web.Response(status=200, body=body, content_type=OCTET_STREAM), 200, None + + +def _ttl(request: web.Request) -> int: + """The ``x-ttl`` header in milliseconds, floor 1000 - the bound on the handler's execution; + a value that is no whole number counts as none.""" + return max(1000, whole_number(request.headers.get(X_TTL)) or 0) + + +def server_port(config: AppConfig) -> int: + """The port ``rest.server.port`` names (8085 without one): a whole number up to 65535, 0 for + one the system picks. The Java engine starts no server for a value it cannot read, without a + word; here such a value stops the start, by name.""" + value = config.get(SERVER_PORT) + port = whole_number(DEFAULT_PORT if value is None else value) + if port is None or port > 65535: + raise AppException(400, f"{SERVER_PORT} must be a port number from 0 to 65535") + return port def _caller_span(request: web.Request, event: EventEnvelope) -> str | None: @@ -236,6 +266,10 @@ def __init__(self, registry: FunctionRegistry | None = None): # REST automation (rest.automation=true): the routing table of rest.yaml, loaded at # construction so a misconfigured entry fails the start, never a request self.rest: RestAutomation | None = RestAutomation.load(app_config(), self) + # read here for the same reason: a keep-alive that is no duration stops the start, and so + # does a log context switch that is neither true nor false + keep_alive_ms() + log_context.enabled(app_config()) async def handle_event(self, request: web.Request) -> web.StreamResponse: try: @@ -302,10 +336,12 @@ async def _deliver(self, service: ServiceDef, event: EventEnvelope, return _transport_error(408, f"Timeout for {ttl} ms") log.info("Handled %s status=%d exec_time=%sms trace_id=%s", event.to, reply.get_status(), reply.exec_time, event.trace_id) + response, status, error = _relay(event.to, reply) if edge: + # the function answered - its own record stands whatever becomes of the reply edge.record_function(event.sender, reply, dispatched, started) - edge.record_edge(200) - return web.Response(status=200, body=reply.to_bytes(), content_type=OCTET_STREAM) + edge.record_edge(status, error) + return response @staticmethod def _refuse(edge: _Edge | None, status: int, message: str) -> web.Response: @@ -342,16 +378,24 @@ async def _dispatch_interceptor(self, request: web.Request, service: ServiceDef, # error contract for an uncaught interceptor exception) log.info("Handled %s status=%d exec_time=%sms trace_id=%s", event.to, first.get_status(), first.exec_time, event.trace_id) + response, status, error = _relay(event.to, first) if edge: - edge.record_edge(200) - return web.Response(status=200, body=first.to_bytes(), - content_type=OCTET_STREAM) + edge.record_edge(status, error) + return response if not capable: # a streaming reply cannot ride a single-shot response if edge: edge.record_edge(406, STREAM_CALLER_REQUIRED) return _transport_error(406, STREAM_CALLER_REQUIRED) - response, status = await self._stream_response(request, queue, first, marker, ttl) + try: + head = envelope_frame(first) + except SERIALIZER_ERRORS as e: + # a head the wire codec refuses, before anything is sent: the single-shot answer + failure = unrendered(event.to, e) + if edge: + edge.record_edge(failure.status, failure.message) + return _transport_error(failure.status, failure.message) + response, status = await self._stream_response(request, queue, first, head, marker, ttl) if edge: # the engines' edge: a stream failing in-band after its head reports # the failure's own status @@ -362,28 +406,28 @@ async def _dispatch_interceptor(self, request: web.Request, service: ServiceDef, async def _stream_response(self, request: web.Request, queue: asyncio.Queue[EventEnvelope], - first: EventEnvelope, first_marker: str, + first: EventEnvelope, head: bytes, first_marker: str, ttl: int) -> tuple[web.StreamResponse, int]: - """Render the envelope-mode SSE dialect: envelope frames for the head, - the terminals and non-text segments; raw frames for plain text. The - x-ttl allowance (overridable by the producer's head control, in - seconds) is the per-segment idle; expiry fails the stream in-band with - the standard 408 error body. Keep-alive comments ride while the - producer is quiet (event.stream.keep.alive, the engines' key).""" + """Render the envelope-mode SSE dialect: envelope frames for the head + (``head``, the first envelope's frame), the terminals and non-text + segments; raw frames for plain text. The x-ttl allowance (overridable + by the producer's head control, a whole number of seconds) is the + per-segment idle; expiry fails the stream in-band with the standard + 408 error body. Keep-alive comments ride while the producer is quiet + (event.stream.keep.alive, the engines' key).""" idle_ms = ttl for key, value in first.headers.items(): if key.lower() == X_TTL: - with contextlib.suppress(ValueError): - seconds = int(str(value).strip()) - if seconds > 0: - idle_ms = seconds * 1000 + seconds = whole_number(value) + if seconds: + idle_ms = seconds * 1000 response = web.StreamResponse(status=first.get_status()) response.headers["content-type"] = TEXT_EVENT_STREAM response.headers.setdefault("cache-control", "no-cache") await response.prepare(request) status = first.get_status() try: - await response.write(envelope_frame(first)) + await response.write(head) if first_marker == DATA: status = await self._stream_segments(response, queue, idle_ms) except ConnectionError: @@ -406,7 +450,14 @@ async def _stream_segments(self, response: web.StreamResponse, frame = envelope_frame(exception_envelope(408, f"Timeout for {seconds} seconds")) await response.write(frame) return 408 - segment = _classify_segment(event) + try: + segment = _classify_segment(event) + except SERIALIZER_ERRORS as e: + # a segment the wire codec refuses fails the stream in band, as an exception does + failure = unrendered(event.sender, e) + frame = envelope_frame(exception_envelope(failure.status, failure.message)) + await response.write(frame) + return failure.status if segment.warn: log.warning("Dropping event - invalid %s signal", "x-event-stream") data, status = segment.frame, segment.status @@ -550,7 +601,7 @@ async def _close_exporter(_app: web.Application) -> None: def run(self, port: int | None = None, host: str = "127.0.0.1") -> None: config = app_config() app_name = config.get_property("application.name", "application") - actual_port = int(port if port is not None else config.get("rest.server.port", 8085)) + actual_port = port if port is not None else server_port(config) app = self.create_app() for route, service in sorted(self.registry.routes().items()): visibility = "PRIVATE" if service.private else "PUBLIC" diff --git a/tests/test_client.py b/tests/test_client.py index 18a808e..c983a3a 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -2,10 +2,20 @@ from collections.abc import AsyncIterator, Callable from contextlib import AbstractAsyncContextManager +from pathlib import Path +import pytest import pytest_asyncio - -from mercury_composable import Body, FunctionRegistry, PostOffice +from aiohttp import web + +from mercury_composable import ( + AppException, + Body, + FunctionRegistry, + PostOffice, + app_config, + load_config, +) from mercury_composable.trace import trace_context @@ -60,3 +70,70 @@ async def test_drop_n_forget_ack(endpoint: str): ack = await po.send("client.echo", body={"fire": "forget"}, timeout_ms=5000) assert ack.get_status() == 202 assert ack.body["delivered"] is True + + +GUARDED_YAML = """\ +rest: + - service: "event.api.service" + methods: ['POST'] + url: "/api/event" + authentication: "client.guard" +""" + + +@pytest_asyncio.fixture +async def guarded(tmp_path: Path, serve: Callable[[FunctionRegistry], AbstractAsyncContextManager[str]] + ) -> AsyncIterator[str]: + """A peer whose /api/event sits behind a REST automation entry with an authentication + function that lets nobody through: the entry answers for the Event API, in JSON.""" + resources = tmp_path / "app" / "resources" + resources.mkdir(parents=True) + (resources / "rest.yaml").write_text(GUARDED_YAML, encoding="utf-8") + load_config(app_dir=str(tmp_path / "app")) + app_config().set("rest.automation", True) + registry = build_registry() + + async def guard(_headers: dict[str, str], _body: Body): + return False + + registry.register("client.guard", guard) + try: + async with serve(registry) as base: + yield f"{base}/api/event" + finally: + load_config() + + +async def test_an_edge_level_rest_error_is_the_failure_it_carries(guarded: str): + """The peer's edge answered for the Event API - JSON, not an envelope: request() and send() + return the failure it carries, as stream() and the engines' client do.""" + async with PostOffice(endpoint=guarded) as po: + reply = await po.request("client.echo", body={"hello": "world"}, timeout_ms=5000) + assert reply.get_status() == 401 + assert reply.body == "Unauthorized" + ack = await po.send("client.echo", body={"fire": "forget"}, timeout_ms=5000) + assert ack.get_status() == 401 + assert ack.body == "Unauthorized" + streamed = [segment async for segment in po.stream("client.echo", body={}, timeout_ms=5000)] + assert [(s.get_status(), s.body) for s in streamed] == [(401, "Unauthorized")] + + +async def test_a_reply_that_is_neither_an_envelope_nor_a_rest_error_is_still_raised(): + """A peer that answers something else - a proxy's page, JSON that is no error body - is not + read as a failure the function sent: the call raises, as it did.""" + async def page(_request: web.Request) -> web.Response: + return web.json_response({"type": "notice", "message": "maintenance"}, status=503) + + app = web.Application() + app.router.add_post("/api/event", page) + runner = web.AppRunner(app) + await runner.setup() + await web.TCPSite(runner, "127.0.0.1", 0).start() + try: + async with PostOffice(endpoint=f"http://127.0.0.1:{runner.addresses[0][1]}/api/event") as po: + with pytest.raises(AppException) as raised: + await po.request("client.echo", body={}, timeout_ms=5000) + finally: + await runner.cleanup() + assert raised.value.status == 503 + assert raised.value.message.startswith("Invalid event-over-http response - ") diff --git a/tests/test_config.py b/tests/test_config.py index 030eb7b..bcfb9b7 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,13 +1,31 @@ -"""AppConfig tests: resources/ convention, -D overrides, ${ENV:default} substitution.""" +"""AppConfig tests: resources/ convention, -D overrides, ${ENV:default} substitution, and the +shared vectors of how a YAML file, a number, a duration and a switch are read.""" +import hashlib +import json +import logging import os import subprocess import sys from pathlib import Path +from typing import Any import pytest +import yaml from mercury_composable import AppConfig +from mercury_composable.config import ( + duration_ms, + load_yaml, + property_text, + switch_value, + whole_number, +) + +VECTORS = Path(__file__).parent / "vectors" / "config-vectors.json" +# the Node twin pins the same digest: change the file in both packs or in neither +VECTORS_SHA256 = "2b6b7fb3d9f73f1cbce4ac169b954577183d8cd8f1a824e9e2b10723199f161e" +KINDS = {type(None): "null", bool: "boolean", int: "integer", float: "float", str: "text"} def write(path: str, text: str) -> None: @@ -174,3 +192,182 @@ def test_the_application_folder_is_known(tmp_path: Path): config = AppConfig(str(other), argv=[], app_dir=str(app_dir)) assert config.app_dir == str(app_dir) assert config.resources_dir == str(tmp_path / "conf") + + +# ---- the shared vectors: one file, read the same way by both packs ---- + +@pytest.fixture(scope="module") +def vectors() -> dict[str, Any]: + with open(VECTORS, encoding="utf-8") as f: + return json.load(f) + + +def loaded(tmp_path: Path, text: str, overrides: dict[str, str] | None = None) -> AppConfig: + """The configuration of an application.yml with this text, under these -D overrides.""" + path = str(tmp_path / "application.yml") + write(path, text) + return AppConfig(path=path, argv=[f"-D{key}={value}" for key, value in (overrides or {}).items()]) + + +def test_the_vector_file_is_the_one_the_node_twin_runs(vectors: dict[str, Any]): + digest = hashlib.sha256(VECTORS.read_bytes()).hexdigest() + assert digest == VECTORS_SHA256, "update both packs' pins when the shared file changes" + assert vectors["version"] == 2 + + +def test_vectors_scalar_cases(vectors: dict[str, Any], tmp_path: Path): + """What a setting's reader receives for every scalar of the list: the kind of value from + ``get``, the text from ``get_property`` - or a file that does not load. The expected values + are those of YAML 1.2.2's core schema, from a reference written from the specification.""" + for case in vectors["scalar_cases"]: + text = f"k: {case['yaml']}\n" + if case["kind"] == "error": + with pytest.raises(yaml.YAMLError): + loaded(tmp_path, text) + continue + config = loaded(tmp_path, text) + assert KINDS[type(config.get("k"))] == case["kind"], case["yaml"] + assert config.get_property("k") == case["text"], case["yaml"] + + +def test_vectors_key_cases(vectors: dict[str, Any], tmp_path: Path): + for case in vectors["key_cases"]: + config = loaded(tmp_path, case["yaml"]) + for key, expected in case["expect"].items(): + assert config.get_property(key) == expected, (case["name"], key) + assert config.exists("") is False, case["name"] + + +def test_vectors_reference_cases(vectors: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + for case in vectors["reference_cases"]: + with monkeypatch.context() as patch: + for name in case.get("unset", []): + patch.delenv(name, raising=False) + for name, value in case.get("env", {}).items(): + patch.setenv(name, value) + config = loaded(tmp_path, case["file"], case.get("overrides")) + defaults = case.get("defaults", {}) + for key, expected in case["expect"].items(): + assert config.get_property(key, defaults.get(key)) == expected, (case["name"], key) + if key in defaults: + # a key read with a default gives the same from get: the cases with one hold text + assert config.get(key, defaults[key]) == expected, (case["name"], key) + for key, kind in case.get("kinds", {}).items(): + assert KINDS[type(config.get(key))] == kind, (case["name"], key) + + +def test_vectors_default_cases(vectors: dict[str, Any], tmp_path: Path): + """A key written without a value is a key that is not there: the default, as in the engine.""" + for case in vectors["default_cases"]: + config = loaded(tmp_path, case["file"], case.get("overrides")) + for key, expected in case["expect"].items(): + assert config.get_property(key, case["defaults"][key]) == expected, (case["name"], key) + assert config.get(key, case["defaults"][key]) == expected, (case["name"], key) + + +def test_the_spellings_of_yaml_1_1_are_text_and_a_leading_zero_is_no_octal(tmp_path: Path): + """The file is read by YAML 1.2.2: what only YAML 1.1 takes for a boolean or a number is text, + ``010`` is ten, ``0o10`` is eight, and ``<<`` is a key like any other.""" + config = loaded(tmp_path, "a: yes\nb: 16_000\nc: 1:30\nd: 0b101\ne: 2026-11-30\nf: 010\ng: 0o10\n" + "h: =\ni: On\nj: 0x1F\nk: 1e3\n<<:\n x: 1\n") + assert {key: config.get(key) for key in "abcdehi"} == { + "a": "yes", "b": "16_000", "c": "1:30", "d": "0b101", "e": "2026-11-30", "h": "=", "i": "On"} + assert [config.get(key) for key in "fgj"] == [10, 8, 31] + assert config.get_property("k") == "1000.0" + assert config.get("<<.x") == 1 + + +def test_a_companion_file_is_read_by_the_same_reader(): + """``load_yaml`` reads any YAML text of the pack - a companion file of an extension too - and + ``property_text`` gives the text a setting reads of a value that is not text.""" + data = load_yaml("a: 010\nb: 1.0\nc: yes\nd: ~\ne: [true, 2.50, 0o17]\nf:\n g: 1e3\n") + assert data == {"a": 10, "b": 1.0, "c": "yes", "d": None, "e": [True, 2.5, 15], "f": {"g": 1000.0}} + assert [property_text(value) for value in (data["a"], data["b"], data["e"][0], data["e"][1], data["f"]["g"])] \ + == ["10", "1.0", "true", "2.5", "1000.0"] + assert load_yaml("") is None + with pytest.raises(yaml.YAMLError): + load_yaml("a: !!binary aGVsbG8=\n") + + +def test_a_tag_outside_the_core_schema_does_not_load(tmp_path: Path): + """The core schema's tags and no other: a scalar under one is valid when its content is one + of the tag's forms, and under ``!`` it is text.""" + config = loaded(tmp_path, "a: !!float 1\nb: !!int '0x1F'\nc: !!str 010\nd: ! 010\ne: !!null ~\n") + assert [config.get_property(key) for key in "abcde"] == ["1.0", "31", "010", "010", None] + for text in ("a: !!binary aGVsbG8=\n", "a: !!timestamp 2026-11-30\n", "a: !!set {a, b}\n", "a: !!int 1_0\n", + "a: !!bool yes\n", "a: !custom x\n"): + with pytest.raises(yaml.YAMLError): + loaded(tmp_path, text) + + +def test_a_value_its_references_leave_empty_reads_as_its_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """``'${NAME:}'`` is the idiom for an optional setting: unset, the key reads as its default, + as in the Java engine; an empty text written as one stays an empty text.""" + monkeypatch.delenv("MERCURY_TEST_EFFORT", raising=False) + config = loaded(tmp_path, "llm.effort: '${MERCURY_TEST_EFFORT:}'\nliteral: ''\n") + assert config.get("llm.effort") is None + assert config.get("llm.effort", "medium") == "medium" + assert config.get_property("llm.effort", "medium") == "medium" + assert config.get_property("literal", "dflt") == "" + # where a text is resolved, not a key read, nothing changes: an empty text stays one + assert config.resolve_property("${MERCURY_TEST_EFFORT:}") == "" + monkeypatch.setenv("MERCURY_TEST_EFFORT", "high") + assert config.get("llm.effort", "medium") == "high" + + +def test_an_override_set_to_none_clears_the_key(tmp_path: Path): + """``set(key, None)`` leaves the key without a value - its default - and never uncovers the + value the file holds; a later ``set`` gives it one again.""" + config = loaded(tmp_path, "a: text\nuses: ${a:fallback}\n") + assert config.get("a", "dflt") == "text" + config.set("a", None) + assert config.get("a", "dflt") == "dflt" + assert config.get("a") is None + assert config.get_property("a", "dflt") == "dflt" + assert config.get("uses") == "fallback" + assert config.exists("a") is True + config.set("a", "again") + assert config.get("a", "dflt") == "again" + + +def test_vectors_number_duration_and_switch_cases(vectors: dict[str, Any]): + for case in vectors["whole_number_cases"]: + assert whole_number(case["value"]) == case["number"], case + for case in vectors["duration_cases"]: + assert duration_ms(case["value"]) == case["ms"], case + for case in vectors["switch_cases"]: + assert switch_value(case["value"], case["default"]) is case["switch"], case + + +def test_a_reference_sees_a_d_argument_and_a_set_override(tmp_path: Path): + """``${flag:false}`` with ``-Dflag=true`` is true, as in the Java engine, where a reference + reads the system property before the file; ``set`` is the same override, made at run time.""" + text = "flag: false\nuses: ${flag:false}\nother: ${late:none}\n" + assert loaded(tmp_path, text).get("uses") is False + config = loaded(tmp_path, text, {"flag": "true"}) + assert config.get("uses") == "true" + assert config.get("other") == "none" + config.set("late", "set") + assert config.get("other") == "set" + config.set("flag", False) + assert config.get("uses") is False + + +def test_a_reference_loop_is_logged_and_has_no_value(tmp_path: Path, caplog: pytest.LogCaptureFixture): + config = loaded(tmp_path, "a: ${b:1}\nb: ${a:2}\nc: ${c}\n") + with caplog.at_level(logging.WARNING, logger="mercury.config"): + assert config.get("a") == "2" + assert config.get("c", "default") == "default" + assert [record.getMessage() for record in caplog.records] == \ + ["Config loop for 'a' detected", "Config loop for 'c' detected"] + + +def test_resolve_property_is_the_text_a_value_reads_as(tmp_path: Path): + config = loaded(tmp_path, "flag: true\nrate: 1.0\n") + assert config.resolve_text("${flag}") is True + assert config.resolve_property("${flag}") == "true" + assert config.resolve_text("${rate}") == 1.0 + assert config.resolve_property("${rate}") == "1.0" + assert config.resolve_property("is ${flag} at ${rate}") == "is true at 1.0" + assert config.resolve_property("${NOT_SET_ANYWHERE}") is None + assert config.resolve_property("plain") == "plain" diff --git a/tests/test_log_context.py b/tests/test_log_context.py index 31580e8..f107e14 100644 --- a/tests/test_log_context.py +++ b/tests/test_log_context.py @@ -5,18 +5,28 @@ import json import logging from collections.abc import Iterator +from pathlib import Path import pytest -from mercury_composable import trace_context, update_context +from mercury_composable import ( + AppConfig, + AppException, + FunctionRegistry, + log_context, + trace_context, + update_context, +) from mercury_composable.config import app_config from mercury_composable.log import EngineJsonFormatter from mercury_composable.log_context import ( LogContextConfig, default_template, + enabled, log_context_config, reset_for_test, ) +from mercury_composable.server import EventApiServer from mercury_composable.trace import TraceInfo @@ -95,6 +105,57 @@ def test_structured_formatter_emits_the_context_block(): assert "context" not in json.loads(formatter.format(record)) +def test_the_template_file_is_read_as_every_yaml_file_of_the_pack(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """app-log-context.yaml goes through the pack's one reader, YAML 1.2.2: what only YAML 1.1 + takes for a boolean or a number is text, a constant that is not text is the text a setting + reads, and an entry without a value is dropped, as the engines drop it.""" + (tmp_path / "application.yml").write_text("application.name: demo\n", encoding="utf-8") + (tmp_path / "app-log-context.yaml").write_text( + "context:\n trace: $traceId\n word: yes\n flag: true\n rate: 1.0\n zero: 010\n count: 16_000\n" + " none:\n quoted: 'on'\n empty: ''\n", encoding="utf-8") + config = AppConfig(path=str(tmp_path / "application.yml"), argv=[]) + monkeypatch.setattr(log_context, "app_config", lambda: config) + reset_for_test() + assert log_context_config().render(info_under_test()) == { + "trace": "4bf92f3577b34da6a3ce929d0e0e4736", "word": "yes", "flag": "true", "rate": "1.0", "zero": "10", + "count": "16_000", "quoted": "on", "empty": ""} + + +def test_a_constant_given_in_code_is_the_text_a_setting_reads(): + context = LogContextConfig({"flag": True, "count": 3, "ratio": 0.5, "none": None}).render(info_under_test()) + assert context == {"flag": "true", "count": "3", "ratio": "0.5"} + + +# the values a switch is read from, and what it is set to: None for one that is refused +SWITCH_PROBES = [(True, True), ("true", True), ("TRUE", True), ("tRuE", True), (False, False), ("false", False), + ("False", False), ("yes", None), ("no", None), ("on", None), ("off", None), ("1", None), (1, None), + (0, None), (" true ", None), ("maybe", None)] + + +def test_the_switch_is_true_or_false_and_on_without_a_value(): + config = AppConfig(argv=[]) + assert enabled(config) is True + config.set("app.log.context", "") + assert enabled(config) is True + for value, expected in SWITCH_PROBES: + config.set("app.log.context", value) + if expected is None: + with pytest.raises(AppException) as refusal: + enabled(config) + assert (refusal.value.status, refusal.value.message) == (400, "app.log.context must be true or false") + else: + assert enabled(config) is expected, value + + +def test_a_switch_that_is_neither_stops_the_host_by_name(): + app_config().set("app.log.context", "off") + with pytest.raises(AppException) as refusal: + EventApiServer(FunctionRegistry()) + assert refusal.value.message == "app.log.context must be true or false" + app_config().set("app.log.context", "FALSE") + assert EventApiServer(FunctionRegistry()).registry.routes() == {} + + def test_feature_flag_disables_the_context_block(): app_config().set("app.log.context", "false") reset_for_test() diff --git a/tests/test_mcp_binding.py b/tests/test_mcp_binding.py index de514ed..b7718b5 100644 --- a/tests/test_mcp_binding.py +++ b/tests/test_mcp_binding.py @@ -353,6 +353,21 @@ def test_the_server_file_is_checked_before_any_connection(servers: Any, entry: d assert message in str(failure.value), str(failure.value) +def test_the_server_file_is_read_as_every_yaml_file_of_the_pack(tmp_path: Path) -> None: + """mcp-servers.yml goes through the pack's one reader, YAML 1.2.2: what only YAML 1.1 takes for a + boolean or a number is text, and a value that is not text is the text a setting reads - the same + arguments and the same environment reach the server from both packs.""" + path = tmp_path / "mcp-servers.yml" + path.write_text( + "servers:\n s:\n transport: stdio\n command: run\n args: [yes, 010, true, 1.0, 16_000]\n" + " env:\n WORD: on\n FLAG: true\n RATIO: 2.0\n ZERO: 010\n timeout_ms: 2000\n", + encoding="utf-8") + spec = binding.load_servers(str(path))[0] + assert spec.args == ("yes", "10", "true", "1.0", "16_000") + assert spec.env == {"WORD": "on", "FLAG": "true", "RATIO": "2.0", "ZERO": "10"} + assert spec.timeout_ms == 2000 + + def test_an_empty_server_map_loads_no_server(servers: Any, caplog: pytest.LogCaptureFixture) -> None: servers({}) with caplog.at_level(logging.WARNING): diff --git a/tests/test_otel_forwarder.py b/tests/test_otel_forwarder.py index eabc74b..dbfcd37 100644 --- a/tests/test_otel_forwarder.py +++ b/tests/test_otel_forwarder.py @@ -13,7 +13,7 @@ import pytest_asyncio from aiohttp import web -from mercury_composable import AppConfig, Body, FunctionRegistry, __version__ +from mercury_composable import AppConfig, AppException, Body, FunctionRegistry, __version__ from mercury_composable.otel import ( DISTRIBUTED_TRACE_FORWARDER, INSTRUMENTATION_SCOPE, @@ -26,6 +26,7 @@ parse_headers, span_from_dataset, ) +from mercury_composable.otel import enabled as otel_enabled from mercury_composable.otel.span import ( KIND_INTERNAL, KIND_SERVER, @@ -481,6 +482,36 @@ def _config(**keys: str) -> AppConfig: return config +# the values a switch is read from, and what it is set to: None for one that is refused +SWITCH_PROBES: list[tuple[Any, bool | None]] = [ + (True, True), ("true", True), ("TRUE", True), ("tRuE", True), (False, False), ("false", False), + ("False", False), ("yes", None), ("no", None), ("on", None), ("off", None), ("1", None), (1, None), + (0, None), (" true ", None), ("maybe", None)] + + +def test_the_switch_is_true_or_false_and_off_without_a_value() -> None: + config = AppConfig(argv=[]) + assert otel_enabled(config) is False + config.set("otel.forwarding", "") + assert otel_enabled(config) is False + for value, expected in SWITCH_PROBES: + config.set("otel.forwarding", value) + if expected is None: + with pytest.raises(AppException) as refusal: + otel_enabled(config) + assert (refusal.value.status, refusal.value.message) == (400, "otel.forwarding must be true or false") + else: + assert otel_enabled(config) is expected, value + + +def test_a_switch_that_is_neither_stops_the_start_by_name() -> None: + registry = FunctionRegistry() + with pytest.raises(AppException) as refusal: + activate(_config(otel_forwarding="yes"), registry) + assert refusal.value.message == "otel.forwarding must be true or false" + assert not registry.exists(DISTRIBUTED_TRACE_FORWARDER) + + def test_the_switch_is_the_only_thing_that_turns_it_on() -> None: registry = FunctionRegistry() assert activate(_config(), registry) is None diff --git a/tests/test_rest_automation.py b/tests/test_rest_automation.py index cd9b227..5a2dc31 100644 --- a/tests/test_rest_automation.py +++ b/tests/test_rest_automation.py @@ -28,6 +28,8 @@ get_trace, load_config, ) +from mercury_composable.event_stream import keep_alive_ms +from mercury_composable.rest_automation import RestAutomation from mercury_composable.rest_routing import ( CorsInfo, HeaderTransform, @@ -40,6 +42,7 @@ parse_cookies, parse_query, parse_timeout, + parse_upload, render_payload, stream_text, ) @@ -48,7 +51,7 @@ Serve = Callable[[FunctionRegistry], AbstractAsyncContextManager[str]] VECTORS = Path(__file__).parent / "vectors" / "rest-automation-vectors.json" # the Node twin pins the same digest: change the file in both packs or in neither -VECTORS_SHA256 = "02fb140f780a9b781dc6cfc7a1c48b1b8094a089cae350dbf5e813754517a51d" +VECTORS_SHA256 = "d7fdef7f56529bdc1faffdefda87bb1cfc70c91600faa8049940e2c594ca3d24" MY_CID = "my_correlation_id" @@ -74,7 +77,7 @@ def _route_view(route: Any) -> dict[str, Any]: def test_the_vector_file_is_the_one_the_node_twin_runs(vectors: dict[str, Any]): digest = hashlib.sha256(VECTORS.read_bytes()).hexdigest() assert digest == VECTORS_SHA256, "update both packs' pins when the shared file changes" - assert vectors["version"] == 3 + assert vectors["version"] == 5 def test_vectors_load_cases(vectors: dict[str, Any]): @@ -228,6 +231,30 @@ def test_vectors_upload_read_cases(vectors: dict[str, Any]): assert files == expect["files"], case["name"] +UPLOAD_BOUND = 16 * 1024 * 1024 + + +def _upload_body(case: dict[str, Any]) -> bytes: + """A case's body: text, or base64 where the bytes are no UTF-8.""" + return base64.b64decode(case["body_base64"]) if "body_base64" in case else case["body"].encode("utf-8") + + +def test_vectors_upload_cases(vectors: dict[str, Any]): + for case in vectors["upload_cases"]: + bound = case.get("bound", UPLOAD_BOUND) + if "error" in case: + with pytest.raises(AppException) as raised: + parse_upload(_upload_body(case), case["content_type"], bound) + assert raised.value.status == case["status"], case["name"] + assert raised.value.message == case["error"], case["name"] + continue + files, fields = parse_upload(_upload_body(case), case["content_type"], bound) + found = [{"name": f.name, "content_type": f.content_type, "size": f.size, "tag": f.tag, + "content_base64": base64.b64encode(f.content).decode("ascii")} for f in files] + assert found == case["files"], case["name"] + assert fields == case["fields"], case["name"] + + def test_vectors_response_cases(vectors: dict[str, Any]): for case in vectors["response_cases"]: spec = case["transform"] @@ -915,6 +942,64 @@ async def test_default_entries_serve_the_host_paths(rest_url: str): assert status == 200 +NAMES_YAML = """\ +rest: + - service: "names.view" + methods: ['GET', 'POST'] + url: "/names/{__proto__}/{constructor}" + authentication: "names.auth" + upload: true +""" +# what the function behind the entry sees of the requests of the test below, the same in both packs +NAMES_SEEN: dict[str, Any] = { + "path": {"__proto__": "one", "constructor": "two"}, + "query": {"__proto__": "q1", "constructor": ["q2", "q3"], "toString": "q4"}, + "cookies": {"__proto__": "k1", "constructor": "k2"}, + "session": {"__proto__": "s1", "constructor": "s2"}, + "header": "h1", + "absent": {"query": True, "cookie": True, "session": True, "path": True}, +} + + +async def test_a_name_every_object_of_the_twin_carries_is_a_name_like_any_other(tmp_path: Path, serve: Serve): + """``__proto__``, ``constructor`` and ``toString`` - names every object of the Node.js twin + carries - as a query parameter, a form field, an upload's field, a cookie, a header, a path + parameter and a session key reach the function as plain values, and one the request does not + hold reads as any name it does not hold: the same request reads the same in both packs.""" + registry = FunctionRegistry() + + async def auth(_headers: dict[str, str], _body: Body): + return EventEnvelope().set_header("__proto__", "s1").set_header("constructor", "s2").set_body(True) + + async def view(_headers: dict[str, str], body: Body): + request = AsyncHttpRequest(body) + return {"path": request.path_parameters, "query": request.query_parameters_map, + "cookies": request.cookies, "session": request.session, "header": request.header("__proto__"), + "absent": {"query": request.query_parameter("valueOf") is None, + "cookie": request.cookie("toString") is None, + "session": request.session_info("toString") is None, + "path": request.path_parameter("toString") is None}} + + registry.register("names.auth", auth) + registry.register("names.view", view) + sent = {"Cookie": "__proto__=k1; constructor=k2", "__proto__": "h1"} + with configured(tmp_path, NAMES_YAML): + async with serve(registry) as base: + url = f"{base}/names/one/two" + status, _, body = await http(f"{url}?__proto__=q1&constructor=q2&constructor=q3&toString=q4", headers=sent) + assert status == 200 + assert json.loads(body) == NAMES_SEEN + # a form's fields, and an upload's, join the query parameters under the same names + status, _, body = await http(url, "POST", {**sent, "Content-Type": "application/x-www-form-urlencoded"}, + "__proto__=q1&constructor=q2&constructor=q3&toString=q4") + assert status == 200 + assert json.loads(body) == {**NAMES_SEEN, "query": {**NAMES_SEEN["query"], "constructor": "q3"}} + headers, multipart = multipart_body(text_field("__proto__", "q1"), text_field("toString", "q4")) + status, _, body = await http(url, "POST", {**sent, **headers}, multipart) + assert status == 200 + assert json.loads(body) == {**NAMES_SEEN, "query": {"__proto__": "q1", "toString": "q4"}} + + DEFAULT_OVERRIDE_YAML = """\ rest: - service: "event.api.service" @@ -1444,3 +1529,278 @@ async def test_a_segment_that_cannot_be_rendered_fails_the_stream_in_band_and_is edge = await _edge_record(probe, "/api/unrenderable/lines") assert edge["status"] == 500 assert edge["exception"] == "Reply cannot be rendered" + + +# ---- the loose ends: one rule for a setting, an upload, a refusal ---- + +async def test_the_edge_reads_every_upload_case_as_the_reader_does( + tmp_path: Path, probe: Probe, serve: Serve, vectors: dict[str, Any] +): + """Every upload case of the shared vectors through the edge over HTTP: the files and the + fields a function receives, or the engines' error body with the reader's status and message.""" + by_bound: dict[int, list[dict[str, Any]]] = {} + for case in vectors["upload_cases"]: + by_bound.setdefault(case.get("bound", UPLOAD_BOUND), []).append(case) + for bound, cases in by_bound.items(): + with configured(tmp_path, REST_YAML, {"rest.upload.max.bytes": bound}): + async with serve(build_registry(probe)) as base: + for case in cases: + headers = {"Content-Type": case["content_type"], "Accept": "application/json"} + status, _, body = await http(f"{base}/api/upload", "POST", headers, _upload_body(case)) + reply = json.loads(body) + if "error" in case: + assert status == case["status"], case["name"] + assert reply == {"status": case["status"], "message": case["error"], + "type": "error"}, case["name"] + continue + assert status == 200, case["name"] + assert reply["files"] == [ + {"name": f["name"], "type": f["content_type"], "size": f["size"], "tag": f["tag"], + "sha256": hashlib.sha256(base64.b64decode(f["content_base64"])).hexdigest()} + for f in case["files"]], case["name"] + assert reply["query"] == case["fields"], case["name"] + + +async def test_an_upload_that_outgrows_its_bound_by_more_than_its_framing_is_refused_unread( + tmp_path: Path, probe: Probe, serve: Serve +): + """The body is read within the bound and the megabyte its delimiters and headers may take: + one that outgrows that is the 413 of the bound, whatever its parts would have been.""" + headers = {"Content-Type": f"multipart/form-data; boundary={BOUNDARY}", "Accept": "application/json"} + with configured(tmp_path, REST_YAML, {"rest.upload.max.bytes": 40}): + async with serve(build_registry(probe)) as base: + status, _, body = await http(f"{base}/api/upload", "POST", headers, b"x" * (40 + 1024 * 1024 + 1)) + assert status == 413 + assert json.loads(body) == {"status": 413, "message": "Upload exceeds 40 bytes", "type": "error"} + # a body that small is read, and refused for what it is + status, _, body = await http(f"{base}/api/upload", "POST", headers, b"x" * (40 + 1024 * 1024)) + assert status == 400 + assert json.loads(body)["message"] == \ + "Invalid multipart body - no part is delimited by the boundary the content type declares" + + +OVERRIDE_YAML = """\ +rest: + - service: "plain.text" + methods: ['POST'] + url: "/api/override" + tracing: ${rest.test.flag:false} + timeout: ${rest.test.timeout:10s} +""" + + +def test_a_reference_in_rest_yaml_sees_an_override(tmp_path: Path, probe: Probe): + """``tracing: ${flag:false}`` with ``-Dflag=true`` is on, as in the Java engine: a reference + reads the key as a key is read - an override before the file's value.""" + write(tmp_path / "app" / "resources" / "application.yml", "rest.test.flag: false\n") + with configured(tmp_path, OVERRIDE_YAML): + server = EventApiServer(build_registry(probe)) + assert server.rest is not None + entry = server.rest.table.find("POST", "/api/override") + assert entry is not None + assert entry.info.tracing is False + assert entry.info.timeout_ms == 10000 + with configured(tmp_path, OVERRIDE_YAML, {"rest.test.flag": "true", "rest.test.timeout": "45s"}): + server = EventApiServer(build_registry(probe)) + assert server.rest is not None + entry = server.rest.table.find("POST", "/api/override") + assert entry is not None + assert entry.info.tracing is True + assert entry.info.timeout_ms == 45000 + + +KEEP_ALIVE_RULE = ("event.stream.keep.alive must be a duration such as 30s, 2m or 500ms" + " (seconds, ms, s, m, h, d), or 0 for none") +UPLOAD_BOUND_RULE = "rest.upload.max.bytes must be a whole number >= 0" +TIMEOUT_RULE = "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" +WRONG_SETTINGS: list[tuple[str, Any, str]] = [ + ("rest.automation", "maybe", "rest.automation must be true or false"), + ("rest.automation", "yes", "rest.automation must be true or false"), + ("rest.automation", 1, "rest.automation must be true or false"), + ("rest.automation", " true ", "rest.automation must be true or false"), + ("rest.upload.max.bytes", "12abc", UPLOAD_BOUND_RULE), + ("rest.upload.max.bytes", "1_000", UPLOAD_BOUND_RULE), + ("rest.upload.max.bytes", "0x10", UPLOAD_BOUND_RULE), + ("rest.upload.max.bytes", "1e3", UPLOAD_BOUND_RULE), + ("rest.upload.max.bytes", "40.9", UPLOAD_BOUND_RULE), + ("rest.upload.max.bytes", 40.9, UPLOAD_BOUND_RULE), + ("rest.upload.max.bytes", -5, UPLOAD_BOUND_RULE), + ("rest.upload.max.bytes", "-5", UPLOAD_BOUND_RULE), + ("rest.upload.max.bytes", "", UPLOAD_BOUND_RULE), + ("rest.upload.max.bytes", True, UPLOAD_BOUND_RULE), + ("rest.upload.max.bytes", 9007199254740992, UPLOAD_BOUND_RULE), + ("event.stream.keep.alive", "1.5s", KEEP_ALIVE_RULE), + ("event.stream.keep.alive", "0.5s", KEEP_ALIVE_RULE), + ("event.stream.keep.alive", "1_0s", KEEP_ALIVE_RULE), + ("event.stream.keep.alive", "1e3ms", KEEP_ALIVE_RULE), + ("event.stream.keep.alive", "-1s", KEEP_ALIVE_RULE), + ("event.stream.keep.alive", "soon", KEEP_ALIVE_RULE), + ("event.stream.keep.alive", "", KEEP_ALIVE_RULE), + # longer than a timer of the Node.js twin holds: 2147483647 ms + ("event.stream.keep.alive", "2147483648ms", KEEP_ALIVE_RULE), + ("event.stream.keep.alive", "25d", KEEP_ALIVE_RULE), + ("event.stream.keep.alive", 2147484, KEEP_ALIVE_RULE), + ("app.log.context", "off", "app.log.context must be true or false"), + ("app.log.context", "yes", "app.log.context must be true or false"), + ("app.log.context", 0, "app.log.context must be true or false"), + ("rest.test.timeout", "1_0s", TIMEOUT_RULE), + ("rest.test.timeout", "\u0663s", TIMEOUT_RULE), + ("rest.test.timeout", "1e3", TIMEOUT_RULE), +] + + +@pytest.mark.parametrize(("key", "value", "message"), WRONG_SETTINGS) +def test_a_setting_that_is_wrong_stops_the_start_by_name( + tmp_path: Path, probe: Probe, key: str, value: Any, message: str +): + """A switch that is neither true nor false, a bound that is no whole number, a keep-alive and + an entry's timeout that are no duration: none of them is read as off or as a default.""" + with configured(tmp_path, OVERRIDE_YAML, {key: value}): + registry = build_registry(probe) + with pytest.raises(AppException) as raised: + EventApiServer(registry) + assert raised.value.status == 400 + assert raised.value.message == message + + +@pytest.mark.parametrize("word", ["yes", "Yes", "on", "ON", "no", "off"]) +def test_a_switch_written_yes_or_on_in_the_file_is_refused(tmp_path: Path, probe: Probe, word: str): + """``yes``, ``no``, ``on`` and ``off`` are text in the packs - the Java engine's reader takes + them for booleans, a spelling no guide documents - so a switch written that way in the file is + refused by name: never read as on, and never as off.""" + folder = tmp_path / "app" + write(folder / "resources" / "application.yml", f"rest.automation: {word}\n") + write(folder / "resources" / "rest.yaml", OVERRIDE_YAML) + load_config(app_dir=str(folder)) + try: + assert app_config().get("rest.automation") == word + registry = build_registry(probe) + with pytest.raises(AppException) as raised: + EventApiServer(registry) + assert raised.value.message == "rest.automation must be true or false" + finally: + load_config() + + +RIGHT_SETTINGS: list[tuple[dict[str, Any], int, int]] = [ + ({}, 16 * 1024 * 1024, 30000), + ({"rest.upload.max.bytes": "40", "event.stream.keep.alive": "500ms"}, 40, 500), + ({"rest.upload.max.bytes": 16000.0, "event.stream.keep.alive": 2}, 16000, 2000), + ({"rest.upload.max.bytes": " 0 ", "event.stream.keep.alive": "0"}, 0, 0), + ({"rest.upload.max.bytes": 9007199254740991, "event.stream.keep.alive": "1h"}, 9007199254740991, 3600000), + ({"rest.automation": "TRUE", "event.stream.keep.alive": " 2m "}, 16 * 1024 * 1024, 120000), + ({"event.stream.keep.alive": "2147483647ms", "app.log.context": "FALSE"}, 16 * 1024 * 1024, 2147483647), + ({"event.stream.keep.alive": "24d", "app.log.context": True}, 16 * 1024 * 1024, 2073600000), +] + + +@pytest.mark.parametrize(("settings", "bound", "keep_alive"), RIGHT_SETTINGS) +def test_a_number_and_a_duration_are_read_by_one_rule( + tmp_path: Path, probe: Probe, settings: dict[str, Any], bound: int, keep_alive: int +): + with configured(tmp_path, OVERRIDE_YAML, settings): + server = EventApiServer(build_registry(probe)) + assert server.rest is not None + assert server.rest.upload_max_bytes == bound + assert keep_alive_ms() == keep_alive + + +def test_the_switch_is_off_for_false_no_value_and_an_empty_one(tmp_path: Path, probe: Probe): + for value in (False, "false", "FALSE", "", None): + with configured(tmp_path, OVERRIDE_YAML, {"rest.automation": value}): + assert EventApiServer(build_registry(probe)).rest is None, repr(value) + + +def test_a_heads_x_ttl_is_a_whole_number_of_seconds(): + """The idle allowance a stream's head asks for: digits and nothing else, in both packs.""" + def idle(ttl: str) -> int: + head = EventEnvelope().set_header("x-ttl", ttl) + return RestAutomation._stream_head(head, 30000)[3] + assert idle("5") == 5000 + assert idle(" 5 ") == 5000 + for ttl in ("0", "1_0", "+5", "-5", "5.0", "5e0", "\u0665", "five", ""): + assert idle(ttl) == 30000, ttl + + +FILTER_FAILS_YAML = """\ +rest: + - service: "plain.text" + methods: ['GET'] + url: "/api/text" +static-content: + filter: + path: ["*.html"] + service: "http.request.filter" +""" + + +async def test_a_filter_reply_that_cannot_be_rendered_is_the_engines_500( + tmp_path: Path, probe: Probe, serve: Serve +): + """A filter's own reply is the response when its status is not 200; one that cannot be + rendered is answered as any other such reply - never with the web framework's own page.""" + with configured(tmp_path, FILTER_FAILS_YAML, public={"about.html": "

about

"}): + registry = build_registry(probe) + + async def http_filter(_headers: dict[str, str], _body: Body): + return EventEnvelope().set_status(401).set_header("x-filter", "demo").set_body({"when": {1, 2}}) + + registry.register("http.request.filter", http_filter) + async with serve(registry) as base: + status, lines, body = await http(f"{base}/about.html", headers={"Accept": "application/json"}) + assert status == 500 + assert header(lines, "content-type") == "application/json" + assert body == UNRENDERABLE + assert header(lines, "x-filter") is None + + +TRACED_UPLOAD_YAML = """\ +rest: + - service: "upload.probe" + methods: ['POST'] + url: "/api/traced/upload" + upload: true + tracing: true +""" + + +async def _edge_records(probe: Probe, path: str, count: int) -> list[dict[str, Any]]: + """The edge's ``http.request`` records of the requests for ``path``, once ``count`` are seen.""" + def found() -> list[dict[str, Any]]: + return [d["trace"] for d in probe.datasets + if d["trace"]["service"] == "http.request" and d["trace"]["path"] == path] + await _wait_for(lambda: len(found()) >= count) + return found() + + +async def test_a_refusal_while_the_request_is_read_is_traced(tmp_path: Path, probe: Probe, serve: Serve): + """The engines record a traced request once its trace is resolved: a refusal raised while the + body is read - a 400, a 413 - leaves the edge's record, under the caller's span.""" + trace_id, caller_span = "4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7" + path = "POST /api/traced/upload" + with configured(tmp_path, TRACED_UPLOAD_YAML, {"rest.upload.max.bytes": 40}): + async with serve(build_registry(probe)) as base: + headers, data = multipart_body((["Content-Type: text/plain"], b"x")) + headers["traceparent"] = f"00-{trace_id}-{caller_span}-01" + status, _, body = await http(f"{base}/api/traced/upload", "POST", headers, data) + assert status == 400 + refusal = "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + assert json.loads(body)["message"] == refusal + records = await _edge_records(probe, path, 1) + assert records[0]["status"] == 400 + assert records[0]["success"] is False + assert records[0]["exception"] == refusal + assert records[0]["id"] == trace_id + assert records[0]["parent_span_id"] == caller_span + headers, data = multipart_body(file_part("doc", "a.bin", b"\x01" * 41)) + status, _, body = await http(f"{base}/api/traced/upload", "POST", headers, data) + assert status == 413 + records = await _edge_records(probe, path, 2) + assert records[1]["status"] == 413 + assert records[1]["exception"] == "Upload exceeds 40 bytes" + # an upload the edge takes is recorded as before, once + headers, data = multipart_body(file_part("doc", "a.bin", b"\x01" * 40)) + status, _, _ = await http(f"{base}/api/traced/upload", "POST", headers, data) + assert status == 200 + records = await _edge_records(probe, path, 3) + assert [r["status"] for r in records] == [400, 413, 200] diff --git a/tests/test_server.py b/tests/test_server.py index 86d8504..5e24bbc 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -1,23 +1,33 @@ """Event API host tests: engine-mirrored semantics over real HTTP.""" import asyncio +import base64 from collections.abc import AsyncIterator, Callable from contextlib import AbstractAsyncContextManager +from typing import Any import aiohttp import msgpack +import pytest import pytest_asyncio +from aiohttp.test_utils import make_mocked_request from mercury_composable import ( + AppConfig, AppException, Body, EventEnvelope, + EventStreamWriter, FunctionRegistry, + PostOffice, annotate_trace, get_trace, ) +from mercury_composable.event_stream import SseParser +from mercury_composable.server import _ttl, server_port OCTET = "application/octet-stream" +Serve = Callable[[FunctionRegistry], AbstractAsyncContextManager[str]] def build_registry() -> FunctionRegistry: @@ -204,3 +214,163 @@ async def test_a_body_over_the_hosts_limit_is_a_transport_failure_413(server_url reply = EventEnvelope.from_bytes(await response.read()) assert reply.get_status() == 413 assert reply.body == "Request body exceeds 16777216 bytes" + + +# ---- a reply the wire codec refuses ---- + +UNRENDERABLE = "Reply cannot be rendered" +TRACE_ID = "4bf92f3577b34da6a3ce929d0e0e4736" + + +def unencodable_registry(datasets: list[dict[str, Any]]) -> FunctionRegistry: + """Functions whose reply holds a set - a type MsgPack does not hold - and the forwarder that + collects the trace records.""" + registry = FunctionRegistry() + + async def reply(_headers: dict[str, str], _body: Body): + return {"when": {1, 2}} + + async def manual(_headers: dict[str, str], event: EventEnvelope): + registry.send_event(EventEnvelope(to=event.reply_to, body={"when": {1, 2}})) + + async def head(_headers: dict[str, str], event: EventEnvelope): + out = EventStreamWriter.from_request(event, registry=registry) + out.first(200, "text/event-stream") + # the head carries the first segment's body: one the codec refuses, before anything is sent + out.write({"when": {1, 2}}) + + async def segment(_headers: dict[str, str], event: EventEnvelope): + out = EventStreamWriter.from_request(event, registry=registry) + out.first(200, "text/event-stream") + out.write("one") + out.write("two") + out.write({"when": {1, 2}}) + out.write("four") + out.close() + + async def forwarder(_headers: dict[str, str], body: Body): + trace = body.get("trace") if isinstance(body, dict) else None + if isinstance(trace, dict): + datasets.append(trace) + + registry.register("unit.unencodable", reply) + registry.register("unit.unencodable.manual", manual, interceptor=True) + registry.register("unit.unencodable.head", head, interceptor=True) + registry.register("unit.unencodable.segment", segment, interceptor=True) + registry.register("distributed.trace.forwarder", forwarder, private=True) + return registry + + +async def _records(datasets: list[dict[str, Any]], service: str) -> list[dict[str, Any]]: + """The trace records of a service, once the edge's own record - the last one written - is in.""" + for _ in range(100): + if any(d["service"] == "http.request" for d in datasets): + return [d for d in datasets if d["service"] == service] + await asyncio.sleep(0.02) + raise AssertionError("the edge's record was not seen") + + +def traced(route: str) -> EventEnvelope: + return EventEnvelope(to=route, body={}).set_trace(TRACE_ID, "TEST /unencodable") + + +@pytest.mark.parametrize("route", ["unit.unencodable", "unit.unencodable.manual", "unit.unencodable.head"]) +async def test_a_reply_the_wire_codec_refuses_is_a_500_envelope_and_is_recorded(serve: Serve, route: str): + """An RPC reply, an interceptor's single-shot answer and a stream's head: a reply that cannot + travel is answered with one message, in an envelope as every transport failure is, and the + edge's record carries the status sent - never 200 over the web framework's own page.""" + datasets: list[dict[str, Any]] = [] + async with serve(unencodable_registry(datasets)) as base: + status, reply = await post_event(base, traced(route), extra={"accept": "text/event-stream"}) + assert status == 500 + assert reply.get_status() == 500 + assert reply.body == UNRENDERABLE + edge = await _records(datasets, "http.request") + assert [d["status"] for d in edge] == [500] + assert edge[0]["success"] is False + assert edge[0]["exception"] == UNRENDERABLE + assert edge[0]["id"] == TRACE_ID + + +async def test_the_function_of_an_unencodable_reply_keeps_its_own_record(serve: Serve): + datasets: list[dict[str, Any]] = [] + async with serve(unencodable_registry(datasets)) as base: + status, _ = await post_event(base, traced("unit.unencodable")) + assert status == 500 + await _records(datasets, "http.request") + # the function answered: its round trip is the record of a success + function = [d for d in datasets if d["service"] == "unit.unencodable"] + assert [d["status"] for d in function] == [200] + assert function[0]["success"] is True + assert "round_trip" in function[0] + + +async def test_a_segment_the_wire_codec_refuses_fails_the_stream_in_band(serve: Serve): + datasets: list[dict[str, Any]] = [] + async with serve(unencodable_registry(datasets)) as base: + headers = {"content-type": OCTET, "x-ttl": "10000", "accept": "text/event-stream"} + async with ( + aiohttp.ClientSession() as session, + session.post(f"{base}/api/event", data=traced("unit.unencodable.segment").to_bytes(), + headers=headers) as response, + ): + assert response.status == 200 + frames = list(SseParser().feed(await response.read())) + # the head with the first segment, the segment before the fault, then the failure - + # nothing after it + assert [name for name, _ in frames] == ["envelope", None, "envelope"] + assert EventEnvelope.from_bytes(base64.b64decode(frames[0][1])).body == "one" + assert frames[1][1] == "two" + failure = EventEnvelope.from_bytes(base64.b64decode(frames[2][1])) + assert failure.get_status() == 500 + assert failure.body == {"type": "error", "status": 500, "message": UNRENDERABLE} + edge = await _records(datasets, "http.request") + assert [d["status"] for d in edge] == [500] + + +# ---- settings and headers read by the one rule for a number ---- + +def test_the_port_is_a_whole_number_up_to_65535(): + def port(value: Any) -> int: + config = AppConfig(argv=[], app_dir=None) + if value is not None: + config.set("rest.server.port", value) + return server_port(config) + assert port(None) == 8085 + assert port(9000) == 9000 + assert port("9000") == 9000 + assert port(" 9000 ") == 9000 + assert port(9000.0) == 9000 + assert port(0) == 0 + assert port(65535) == 65535 + for value in ("80_85", "8085.0", "+8085", "0x1F95", "\u0668\u0660\u0668\u0665", "http", "", 8085.5, + -1, 65536, True): + with pytest.raises(AppException) as raised: + port(value) + assert raised.value.message == "rest.server.port must be a port number from 0 to 65535", repr(value) + + +async def test_a_time_to_live_longer_than_a_timer_of_the_twin_holds_waits_for_the_reply(server_url: str): + """3,000,000,000 ms is more than the 2,147,483,647 a timer of the Node.js twin holds: there + the wait is capped at that, here it is as long as asked - the reply arrives either way, and a + caller's header is never refused for its length.""" + for ttl in ("2147483648", "3000000000", "9007199254740991"): + status, reply = await post_event(server_url, EventEnvelope(to="unit.echo", body={"a": 1}), ttl=ttl) + assert status == 200, ttl + assert reply.body["body"] == {"a": 1}, ttl + # and so does a remote call with a timeout of that length + async with PostOffice(endpoint=f"{server_url}/api/event") as po: + for timeout_ms in (3000000000, 5000000000): + reply = await po.request("unit.echo", body={"a": 2}, timeout_ms=timeout_ms) + assert reply.get_status() == 200, timeout_ms + + +def test_the_x_ttl_of_an_event_is_a_whole_number_of_milliseconds(): + def ttl(value: str | None) -> int: + headers = {} if value is None else {"x-ttl": value} + return _ttl(make_mocked_request("POST", "/api/event", headers=headers)) + assert ttl("5000") == 5000 + assert ttl(" 5000 ") == 5000 + assert ttl("500") == 1000 + for value in (None, "", "5_000", "+5000", "-5000", "5000.0", "5e3", "\u0665\u0660\u0660\u0660", "5000ms"): + assert ttl(value) == 1000, repr(value) diff --git a/tests/vectors/config-vectors.json b/tests/vectors/config-vectors.json new file mode 100644 index 0000000..22e570a --- /dev/null +++ b/tests/vectors/config-vectors.json @@ -0,0 +1,2409 @@ +{ + "contract": "configuration", + "version": 2, + "description": "The configuration reader's shared vectors, run by mercury-python and mercury-nodejs against the same file. scalar_cases pin how a YAML file is read: each is the text written after 'k: ' in an application.yml, with the kind of value a setting's reader gets from get (null, boolean, integer, float, text) and the text it gets from get_property / getProperty - or kind error when the file does not load. A plain scalar is resolved by the core schema of YAML 1.2.2 (section 10.3.2 of the specification), its rows tried in order: nothing, ~ and null, also capitalized or in upper case, are no value; true and false, also capitalized or in upper case, a boolean; [-+]?[0-9]+ an integer in base 10, so 010 is ten; 0o[0-7]+ an integer in base 8; 0x[0-9a-fA-F]+ an integer in base 16; a decimal number with a point or an exponent, .inf and .nan a float; anything else, and anything in quotes, text. So yes, no, on and off, a number with an underscore, in base 2 or in base 60, a date, the lone = and << are text. The expected values are the reading of a reference written from the specification, not of either pack. Under an explicit tag a scalar is valid when the core schema has the tag (!!null, !!bool, !!int, !!float, !!str) and the content is one of the tag's rows; under the non-specific tag ! it is text; a document with any other tag does not load. As text, a boolean is true or false and a float keeps its point (16000.0), written as Python writes one. key_cases pin the dotted keys of a document whose mapping keys YAML read as something other than text - the text of that value - and that << is a key like any other, since the core schema has no merge key. reference_cases pin ${name:default}: the environment variable (env; unset names the ones that must be absent), then the key of that name as a key is read - a -D override (overrides) before the file's value - then the default; a reference that leads back to a key being resolved has no value, so its default stands; a value its references leave empty is no value either, as in the Java engine, while an empty text written as one stays one; expect gives get_property per key, null for no value, read with the default a case gives for the key (defaults) - get then returns the same - and kinds the kind of get where a case names it. default_cases pin a key written without a value (key:, a YAML null): it reads as a key that is not there, as in the Java engine, so get_property returns the default given (defaults) - also through a reference to such a key. whole_number_cases, duration_cases and switch_cases pin the one rule for a number, a duration and a switch: number, ms and switch are null for a value that is none - which a setting refuses by name.", + "scalar_cases": [ + { + "yaml": "true", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "True", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "TRUE", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "false", + "kind": "boolean", + "text": "false" + }, + { + "yaml": "False", + "kind": "boolean", + "text": "false" + }, + { + "yaml": "FALSE", + "kind": "boolean", + "text": "false" + }, + { + "yaml": "yes", + "kind": "text", + "text": "yes" + }, + { + "yaml": "Yes", + "kind": "text", + "text": "Yes" + }, + { + "yaml": "YES", + "kind": "text", + "text": "YES" + }, + { + "yaml": "no", + "kind": "text", + "text": "no" + }, + { + "yaml": "No", + "kind": "text", + "text": "No" + }, + { + "yaml": "NO", + "kind": "text", + "text": "NO" + }, + { + "yaml": "on", + "kind": "text", + "text": "on" + }, + { + "yaml": "On", + "kind": "text", + "text": "On" + }, + { + "yaml": "ON", + "kind": "text", + "text": "ON" + }, + { + "yaml": "off", + "kind": "text", + "text": "off" + }, + { + "yaml": "Off", + "kind": "text", + "text": "Off" + }, + { + "yaml": "OFF", + "kind": "text", + "text": "OFF" + }, + { + "yaml": "y", + "kind": "text", + "text": "y" + }, + { + "yaml": "Y", + "kind": "text", + "text": "Y" + }, + { + "yaml": "n", + "kind": "text", + "text": "n" + }, + { + "yaml": "N", + "kind": "text", + "text": "N" + }, + { + "yaml": "tRue", + "kind": "text", + "text": "tRue" + }, + { + "yaml": "yEs", + "kind": "text", + "text": "yEs" + }, + { + "yaml": "oN", + "kind": "text", + "text": "oN" + }, + { + "yaml": "fALSE", + "kind": "text", + "text": "fALSE" + }, + { + "yaml": "~", + "kind": "null", + "text": null + }, + { + "yaml": "null", + "kind": "null", + "text": null + }, + { + "yaml": "Null", + "kind": "null", + "text": null + }, + { + "yaml": "NULL", + "kind": "null", + "text": null + }, + { + "yaml": "", + "kind": "null", + "text": null + }, + { + "yaml": "nULL", + "kind": "text", + "text": "nULL" + }, + { + "yaml": "none", + "kind": "text", + "text": "none" + }, + { + "yaml": "None", + "kind": "text", + "text": "None" + }, + { + "yaml": "nil", + "kind": "text", + "text": "nil" + }, + { + "yaml": "0", + "kind": "integer", + "text": "0" + }, + { + "yaml": "1", + "kind": "integer", + "text": "1" + }, + { + "yaml": "16000", + "kind": "integer", + "text": "16000" + }, + { + "yaml": "-5", + "kind": "integer", + "text": "-5" + }, + { + "yaml": "+5", + "kind": "integer", + "text": "5" + }, + { + "yaml": "16_000", + "kind": "text", + "text": "16_000" + }, + { + "yaml": "1_000", + "kind": "text", + "text": "1_000" + }, + { + "yaml": "010", + "kind": "integer", + "text": "10" + }, + { + "yaml": "0o10", + "kind": "integer", + "text": "8" + }, + { + "yaml": "0O10", + "kind": "text", + "text": "0O10" + }, + { + "yaml": "0x10", + "kind": "integer", + "text": "16" + }, + { + "yaml": "0X10", + "kind": "text", + "text": "0X10" + }, + { + "yaml": "0b101", + "kind": "text", + "text": "0b101" + }, + { + "yaml": "0B101", + "kind": "text", + "text": "0B101" + }, + { + "yaml": "08", + "kind": "integer", + "text": "8" + }, + { + "yaml": "09", + "kind": "integer", + "text": "9" + }, + { + "yaml": "00", + "kind": "integer", + "text": "0" + }, + { + "yaml": "-010", + "kind": "integer", + "text": "-10" + }, + { + "yaml": "+010", + "kind": "integer", + "text": "10" + }, + { + "yaml": "0_", + "kind": "text", + "text": "0_" + }, + { + "yaml": "_1", + "kind": "text", + "text": "_1" + }, + { + "yaml": "1_", + "kind": "text", + "text": "1_" + }, + { + "yaml": "1__0", + "kind": "text", + "text": "1__0" + }, + { + "yaml": "9007199254740991", + "kind": "integer", + "text": "9007199254740991" + }, + { + "yaml": "9007199254740992", + "kind": "integer", + "text": "9007199254740992" + }, + { + "yaml": "9007199254740993", + "kind": "integer", + "text": "9007199254740993" + }, + { + "yaml": "-9007199254740993", + "kind": "integer", + "text": "-9007199254740993" + }, + { + "yaml": "12345678901234567890", + "kind": "integer", + "text": "12345678901234567890" + }, + { + "yaml": "-0", + "kind": "integer", + "text": "0" + }, + { + "yaml": "+0", + "kind": "integer", + "text": "0" + }, + { + "yaml": "0x_10", + "kind": "text", + "text": "0x_10" + }, + { + "yaml": "0xFF_FF", + "kind": "text", + "text": "0xFF_FF" + }, + { + "yaml": "0xff", + "kind": "integer", + "text": "255" + }, + { + "yaml": "-0x10", + "kind": "text", + "text": "-0x10" + }, + { + "yaml": "0b1_0", + "kind": "text", + "text": "0b1_0" + }, + { + "yaml": "0x", + "kind": "text", + "text": "0x" + }, + { + "yaml": "0b", + "kind": "text", + "text": "0b" + }, + { + "yaml": "007", + "kind": "integer", + "text": "7" + }, + { + "yaml": "0_7", + "kind": "text", + "text": "0_7" + }, + { + "yaml": "1 000", + "kind": "text", + "text": "1 000" + }, + { + "yaml": "1:30", + "kind": "text", + "text": "1:30" + }, + { + "yaml": "1:30:00", + "kind": "text", + "text": "1:30:00" + }, + { + "yaml": "-1:30", + "kind": "text", + "text": "-1:30" + }, + { + "yaml": "+1:30", + "kind": "text", + "text": "+1:30" + }, + { + "yaml": "190:20:30", + "kind": "text", + "text": "190:20:30" + }, + { + "yaml": "1:60", + "kind": "text", + "text": "1:60" + }, + { + "yaml": "01:30", + "kind": "text", + "text": "01:30" + }, + { + "yaml": "1:5", + "kind": "text", + "text": "1:5" + }, + { + "yaml": "1:05", + "kind": "text", + "text": "1:05" + }, + { + "yaml": "1:30.5", + "kind": "text", + "text": "1:30.5" + }, + { + "yaml": "1:30.", + "kind": "text", + "text": "1:30." + }, + { + "yaml": "0:0", + "kind": "text", + "text": "0:0" + }, + { + "yaml": "1:30:", + "kind": "error", + "text": null + }, + { + "yaml": "1:2:3:4", + "kind": "text", + "text": "1:2:3:4" + }, + { + "yaml": "1.5", + "kind": "float", + "text": "1.5" + }, + { + "yaml": "16000.0", + "kind": "float", + "text": "16000.0" + }, + { + "yaml": "1.", + "kind": "float", + "text": "1.0" + }, + { + "yaml": ".5", + "kind": "float", + "text": "0.5" + }, + { + "yaml": "-.5", + "kind": "float", + "text": "-0.5" + }, + { + "yaml": "+.5", + "kind": "float", + "text": "0.5" + }, + { + "yaml": "1e3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1E3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1.0e3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1.0e+3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1.0E+3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1e+3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1e-3", + "kind": "float", + "text": "0.001" + }, + { + "yaml": "1.5e3", + "kind": "float", + "text": "1500.0" + }, + { + "yaml": ".5e3", + "kind": "float", + "text": "500.0" + }, + { + "yaml": ".5e+3", + "kind": "float", + "text": "500.0" + }, + { + "yaml": "1_000.5", + "kind": "text", + "text": "1_000.5" + }, + { + "yaml": "1_0.0_1", + "kind": "text", + "text": "1_0.0_1" + }, + { + "yaml": ".inf", + "kind": "float", + "text": "inf" + }, + { + "yaml": ".Inf", + "kind": "float", + "text": "inf" + }, + { + "yaml": ".INF", + "kind": "float", + "text": "inf" + }, + { + "yaml": "-.inf", + "kind": "float", + "text": "-inf" + }, + { + "yaml": "+.inf", + "kind": "float", + "text": "inf" + }, + { + "yaml": ".nan", + "kind": "float", + "text": "nan" + }, + { + "yaml": ".NaN", + "kind": "float", + "text": "nan" + }, + { + "yaml": ".NAN", + "kind": "float", + "text": "nan" + }, + { + "yaml": "inf", + "kind": "text", + "text": "inf" + }, + { + "yaml": "nan", + "kind": "text", + "text": "nan" + }, + { + "yaml": "Infinity", + "kind": "text", + "text": "Infinity" + }, + { + "yaml": "NaN", + "kind": "text", + "text": "NaN" + }, + { + "yaml": "0.0", + "kind": "float", + "text": "0.0" + }, + { + "yaml": "-0.0", + "kind": "float", + "text": "-0.0" + }, + { + "yaml": "1.0", + "kind": "float", + "text": "1.0" + }, + { + "yaml": "1.10", + "kind": "float", + "text": "1.1" + }, + { + "yaml": "100000000000000000000.0", + "kind": "float", + "text": "1e+20" + }, + { + "yaml": "0.1", + "kind": "float", + "text": "0.1" + }, + { + "yaml": "1e400", + "kind": "float", + "text": "inf" + }, + { + "yaml": "1.0e+400", + "kind": "float", + "text": "inf" + }, + { + "yaml": "0.000001", + "kind": "float", + "text": "1e-06" + }, + { + "yaml": "0.00001", + "kind": "float", + "text": "1e-05" + }, + { + "yaml": "1.5E+10", + "kind": "float", + "text": "15000000000.0" + }, + { + "yaml": "+1.5", + "kind": "float", + "text": "1.5" + }, + { + "yaml": "1.e3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1.e+3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1e", + "kind": "text", + "text": "1e" + }, + { + "yaml": "1.5e", + "kind": "text", + "text": "1.5e" + }, + { + "yaml": ".", + "kind": "text", + "text": "." + }, + { + "yaml": "..", + "kind": "text", + "text": ".." + }, + { + "yaml": "-.", + "kind": "text", + "text": "-." + }, + { + "yaml": "1.2.3", + "kind": "text", + "text": "1.2.3" + }, + { + "yaml": "12345678901234567.0", + "kind": "float", + "text": "1.2345678901234568e+16" + }, + { + "yaml": "1e16", + "kind": "float", + "text": "1e+16" + }, + { + "yaml": "1.0e+16", + "kind": "float", + "text": "1e+16" + }, + { + "yaml": "0.1e+1", + "kind": "float", + "text": "1.0" + }, + { + "yaml": "123456789012345680000.0", + "kind": "float", + "text": "1.2345678901234568e+20" + }, + { + "yaml": "1.0e-5", + "kind": "float", + "text": "1e-05" + }, + { + "yaml": "1.0e-7", + "kind": "float", + "text": "1e-07" + }, + { + "yaml": "4.0e+15", + "kind": "float", + "text": "4000000000000000.0" + }, + { + "yaml": "1.0e+15", + "kind": "float", + "text": "1000000000000000.0" + }, + { + "yaml": "9007199254740993.0", + "kind": "float", + "text": "9007199254740992.0" + }, + { + "yaml": "2026-11-30", + "kind": "text", + "text": "2026-11-30" + }, + { + "yaml": "2026-11-30T10:00:00Z", + "kind": "text", + "text": "2026-11-30T10:00:00Z" + }, + { + "yaml": "2026-11-30 10:00:00", + "kind": "text", + "text": "2026-11-30 10:00:00" + }, + { + "yaml": "2026-11-30T10:00:00+08:00", + "kind": "text", + "text": "2026-11-30T10:00:00+08:00" + }, + { + "yaml": "2026-11-30t10:00:00.5Z", + "kind": "text", + "text": "2026-11-30t10:00:00.5Z" + }, + { + "yaml": "2026-1-1", + "kind": "text", + "text": "2026-1-1" + }, + { + "yaml": "2026-13-45", + "kind": "text", + "text": "2026-13-45" + }, + { + "yaml": "2026-11-30T10:00:00", + "kind": "text", + "text": "2026-11-30T10:00:00" + }, + { + "yaml": "2026-11-30 10:00:00 +8", + "kind": "text", + "text": "2026-11-30 10:00:00 +8" + }, + { + "yaml": "2026-11-30T10:00:00.123456789Z", + "kind": "text", + "text": "2026-11-30T10:00:00.123456789Z" + }, + { + "yaml": "2026-02-30", + "kind": "text", + "text": "2026-02-30" + }, + { + "yaml": "10:00:00", + "kind": "text", + "text": "10:00:00" + }, + { + "yaml": "2026-11", + "kind": "text", + "text": "2026-11" + }, + { + "yaml": "20261130", + "kind": "integer", + "text": "20261130" + }, + { + "yaml": "'yes'", + "kind": "text", + "text": "yes" + }, + { + "yaml": "\"yes\"", + "kind": "text", + "text": "yes" + }, + { + "yaml": "'true'", + "kind": "text", + "text": "true" + }, + { + "yaml": "\"16000\"", + "kind": "text", + "text": "16000" + }, + { + "yaml": "'1e3'", + "kind": "text", + "text": "1e3" + }, + { + "yaml": "\"\"", + "kind": "text", + "text": "" + }, + { + "yaml": "''", + "kind": "text", + "text": "" + }, + { + "yaml": "'it''s'", + "kind": "text", + "text": "it's" + }, + { + "yaml": "\"tab\\t\"", + "kind": "text", + "text": "tab\t" + }, + { + "yaml": "\"\\u00e9\"", + "kind": "text", + "text": "é" + }, + { + "yaml": "' 5 '", + "kind": "text", + "text": " 5 " + }, + { + "yaml": "\"010\"", + "kind": "text", + "text": "010" + }, + { + "yaml": "'~'", + "kind": "text", + "text": "~" + }, + { + "yaml": "'null'", + "kind": "text", + "text": "null" + }, + { + "yaml": "'2026-11-30'", + "kind": "text", + "text": "2026-11-30" + }, + { + "yaml": "hello", + "kind": "text", + "text": "hello" + }, + { + "yaml": "hello world", + "kind": "text", + "text": "hello world" + }, + { + "yaml": "12abc", + "kind": "text", + "text": "12abc" + }, + { + "yaml": "1.5s", + "kind": "text", + "text": "1.5s" + }, + { + "yaml": "30s", + "kind": "text", + "text": "30s" + }, + { + "yaml": "1_0s", + "kind": "text", + "text": "1_0s" + }, + { + "yaml": "é", + "kind": "text", + "text": "é" + }, + { + "yaml": "a: b", + "kind": "error", + "text": null + }, + { + "yaml": "a:b", + "kind": "text", + "text": "a:b" + }, + { + "yaml": "http://x:80/y", + "kind": "text", + "text": "http://x:80/y" + }, + { + "yaml": "x # y", + "kind": "text", + "text": "x" + }, + { + "yaml": "x#y", + "kind": "text", + "text": "x#y" + }, + { + "yaml": "- x", + "kind": "error", + "text": null + }, + { + "yaml": "-x", + "kind": "text", + "text": "-x" + }, + { + "yaml": "?x", + "kind": "text", + "text": "?x" + }, + { + "yaml": ":x", + "kind": "text", + "text": ":x" + }, + { + "yaml": "=", + "kind": "text", + "text": "=" + }, + { + "yaml": "<<", + "kind": "text", + "text": "<<" + }, + { + "yaml": "*", + "kind": "error", + "text": null + }, + { + "yaml": "&a x", + "kind": "text", + "text": "x" + }, + { + "yaml": "!x", + "kind": "error", + "text": null + }, + { + "yaml": "%x", + "kind": "error", + "text": null + }, + { + "yaml": "@x", + "kind": "error", + "text": null + }, + { + "yaml": "`x", + "kind": "error", + "text": null + }, + { + "yaml": "|", + "kind": "text", + "text": "" + }, + { + "yaml": ">", + "kind": "text", + "text": "" + }, + { + "yaml": "a,b", + "kind": "text", + "text": "a,b" + }, + { + "yaml": "1,000", + "kind": "text", + "text": "1,000" + }, + { + "yaml": "$5", + "kind": "text", + "text": "$5" + }, + { + "yaml": "true ", + "kind": "boolean", + "text": "true" + }, + { + "yaml": " true", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "TRUE.", + "kind": "text", + "text": "TRUE." + }, + { + "yaml": "0xZZ", + "kind": "text", + "text": "0xZZ" + }, + { + "yaml": "1-2", + "kind": "text", + "text": "1-2" + }, + { + "yaml": "+", + "kind": "text", + "text": "+" + }, + { + "yaml": "-", + "kind": "error", + "text": null + }, + { + "yaml": "--", + "kind": "text", + "text": "--" + }, + { + "yaml": "0.5s", + "kind": "text", + "text": "0.5s" + }, + { + "yaml": "5 m", + "kind": "text", + "text": "5 m" + }, + { + "yaml": "!!str 123", + "kind": "text", + "text": "123" + }, + { + "yaml": "!!str yes", + "kind": "text", + "text": "yes" + }, + { + "yaml": "!!int \"123\"", + "kind": "integer", + "text": "123" + }, + { + "yaml": "!!int 1_0", + "kind": "error", + "text": null + }, + { + "yaml": "!!float 1", + "kind": "float", + "text": "1.0" + }, + { + "yaml": "!!float '1e3'", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "!!bool yes", + "kind": "error", + "text": null + }, + { + "yaml": "!!bool \"true\"", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "!!null ''", + "kind": "null", + "text": null + }, + { + "yaml": "!!binary aGVsbG8=", + "kind": "error", + "text": null + }, + { + "yaml": "!!timestamp 2026-11-30", + "kind": "error", + "text": null + }, + { + "yaml": "!!set {a, b}", + "kind": "error", + "text": null + }, + { + "yaml": "!!omap [a: 1]", + "kind": "error", + "text": null + }, + { + "yaml": "!!python/tuple [1]", + "kind": "error", + "text": null + }, + { + "yaml": "!custom x", + "kind": "error", + "text": null + }, + { + "yaml": "! 5", + "kind": "text", + "text": "5" + }, + { + "yaml": "0o17", + "kind": "integer", + "text": "15" + }, + { + "yaml": "0o", + "kind": "text", + "text": "0o" + }, + { + "yaml": "0o8", + "kind": "text", + "text": "0o8" + }, + { + "yaml": "0o1_0", + "kind": "text", + "text": "0o1_0" + }, + { + "yaml": "+0o10", + "kind": "text", + "text": "+0o10" + }, + { + "yaml": "-0o10", + "kind": "text", + "text": "-0o10" + }, + { + "yaml": "0x1f", + "kind": "integer", + "text": "31" + }, + { + "yaml": "0x1F", + "kind": "integer", + "text": "31" + }, + { + "yaml": "+0x10", + "kind": "text", + "text": "+0x10" + }, + { + "yaml": "0xG", + "kind": "text", + "text": "0xG" + }, + { + "yaml": "00x10", + "kind": "text", + "text": "00x10" + }, + { + "yaml": "0010", + "kind": "integer", + "text": "10" + }, + { + "yaml": "-007", + "kind": "integer", + "text": "-7" + }, + { + "yaml": "1e+", + "kind": "text", + "text": "1e+" + }, + { + "yaml": "e3", + "kind": "text", + "text": "e3" + }, + { + "yaml": ".e3", + "kind": "text", + "text": ".e3" + }, + { + "yaml": "1.e-2", + "kind": "float", + "text": "0.01" + }, + { + "yaml": "-1.", + "kind": "float", + "text": "-1.0" + }, + { + "yaml": "+1.", + "kind": "float", + "text": "1.0" + }, + { + "yaml": "--1", + "kind": "text", + "text": "--1" + }, + { + "yaml": "+-1", + "kind": "text", + "text": "+-1" + }, + { + "yaml": "1+", + "kind": "text", + "text": "1+" + }, + { + "yaml": "1..0", + "kind": "text", + "text": "1..0" + }, + { + "yaml": "1e3.0", + "kind": "text", + "text": "1e3.0" + }, + { + "yaml": ".5.", + "kind": "text", + "text": ".5." + }, + { + "yaml": "+.Inf", + "kind": "float", + "text": "inf" + }, + { + "yaml": "-.INF", + "kind": "float", + "text": "-inf" + }, + { + "yaml": "-.nan", + "kind": "text", + "text": "-.nan" + }, + { + "yaml": "+.nan", + "kind": "text", + "text": "+.nan" + }, + { + "yaml": ".Nan", + "kind": "text", + "text": ".Nan" + }, + { + "yaml": ".iNF", + "kind": "text", + "text": ".iNF" + }, + { + "yaml": ".infinity", + "kind": "text", + "text": ".infinity" + }, + { + "yaml": "~~", + "kind": "text", + "text": "~~" + }, + { + "yaml": "Null ", + "kind": "null", + "text": null + }, + { + "yaml": "nUll", + "kind": "text", + "text": "nUll" + }, + { + "yaml": "tRUE", + "kind": "text", + "text": "tRUE" + }, + { + "yaml": "False.", + "kind": "text", + "text": "False." + }, + { + "yaml": "0b0", + "kind": "text", + "text": "0b0" + }, + { + "yaml": "1__0.5", + "kind": "text", + "text": "1__0.5" + }, + { + "yaml": "12:30:45", + "kind": "text", + "text": "12:30:45" + }, + { + "yaml": "0:30", + "kind": "text", + "text": "0:30" + }, + { + "yaml": "<<:", + "kind": "error", + "text": null + }, + { + "yaml": "= ", + "kind": "text", + "text": "=" + }, + { + "yaml": "2026-11-30 ", + "kind": "text", + "text": "2026-11-30" + }, + { + "yaml": "!!str 010", + "kind": "text", + "text": "010" + }, + { + "yaml": "!!str", + "kind": "text", + "text": "" + }, + { + "yaml": "!!int 010", + "kind": "integer", + "text": "10" + }, + { + "yaml": "!!int 0o10", + "kind": "integer", + "text": "8" + }, + { + "yaml": "!!int 0x10", + "kind": "integer", + "text": "16" + }, + { + "yaml": "!!int '0x1F'", + "kind": "integer", + "text": "31" + }, + { + "yaml": "!!int +7", + "kind": "integer", + "text": "7" + }, + { + "yaml": "!!int 1.0", + "kind": "error", + "text": null + }, + { + "yaml": "!!int 1:30", + "kind": "error", + "text": null + }, + { + "yaml": "!!int 0b11", + "kind": "error", + "text": null + }, + { + "yaml": "!!int", + "kind": "error", + "text": null + }, + { + "yaml": "!!float 1e3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "!!float .inf", + "kind": "float", + "text": "inf" + }, + { + "yaml": "!!float -.INF", + "kind": "float", + "text": "-inf" + }, + { + "yaml": "!!float .NaN", + "kind": "float", + "text": "nan" + }, + { + "yaml": "!!float 0x10", + "kind": "error", + "text": null + }, + { + "yaml": "!!float 1_0", + "kind": "error", + "text": null + }, + { + "yaml": "!!float", + "kind": "error", + "text": null + }, + { + "yaml": "!!bool True", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "!!bool FALSE", + "kind": "boolean", + "text": "false" + }, + { + "yaml": "!!bool on", + "kind": "error", + "text": null + }, + { + "yaml": "!!bool 1", + "kind": "error", + "text": null + }, + { + "yaml": "!!bool", + "kind": "error", + "text": null + }, + { + "yaml": "!!null", + "kind": "null", + "text": null + }, + { + "yaml": "!!null ~", + "kind": "null", + "text": null + }, + { + "yaml": "!!null Null", + "kind": "null", + "text": null + }, + { + "yaml": "!!null x", + "kind": "error", + "text": null + }, + { + "yaml": "!!null 0", + "kind": "error", + "text": null + }, + { + "yaml": "! true", + "kind": "text", + "text": "true" + }, + { + "yaml": "! 010", + "kind": "text", + "text": "010" + }, + { + "yaml": "! ~", + "kind": "text", + "text": "~" + }, + { + "yaml": "!", + "kind": "text", + "text": "" + }, + { + "yaml": "! 'x'", + "kind": "text", + "text": "x" + }, + { + "yaml": "!!merge <<", + "kind": "error", + "text": null + }, + { + "yaml": "!!value =", + "kind": "error", + "text": null + }, + { + "yaml": "!!pairs [a: 1]", + "kind": "error", + "text": null + }, + { + "yaml": "!!seq x", + "kind": "error", + "text": null + }, + { + "yaml": "!!map x", + "kind": "error", + "text": null + }, + { + "yaml": "!!str [1]", + "kind": "error", + "text": null + }, + { + "yaml": "!!int [1]", + "kind": "error", + "text": null + }, + { + "yaml": "! 7", + "kind": "integer", + "text": "7" + }, + { + "yaml": "! 7", + "kind": "text", + "text": "7" + }, + { + "yaml": "! 7", + "kind": "float", + "text": "7.0" + }, + { + "yaml": "! 7", + "kind": "error", + "text": null + }, + { + "yaml": "!e!x 7", + "kind": "error", + "text": null + } + ], + "key_cases": [ + { + "name": "a key YAML read as a boolean, a number or null is the text of that value; a key written yes, no, on or off, with an underscore or in base 60 is that text", + "yaml": "True: a\n~: c\n8080: d\n1.0: e\n0x10: f\n010: o\n0o10: p\n1_0: q\n1:30: r\non: l\n\"quoted\": g\nplain.key: h\nFALSE:\n true: b\noff:\n yes: m\n No: n\nnested:\n 1e3: i\n 2026-11-30: j\n 12345678901234567890: k\n .inf: s\n", + "expect": { + "false.true": "b", + "off.yes": "m", + "off.No": "n", + "nested.1000.0": "i", + "nested.2026-11-30": "j", + "nested.12345678901234567890": "k", + "nested.inf": "s", + "true": "a", + "null": "c", + "8080": "d", + "1.0": "e", + "16": "f", + "10": "o", + "8": "p", + "1_0": "q", + "1:30": "r", + "on": "l", + "quoted": "g", + "plain.key": "h" + } + }, + { + "name": "a document that is not a mapping has no keys - a list", + "yaml": "- a\n- b\n", + "expect": {} + }, + { + "name": "a document that is not a mapping has no keys - a lone scalar", + "yaml": "hello\n", + "expect": {} + }, + { + "name": "a document that is not a mapping has no keys - an empty file", + "yaml": "", + "expect": {} + }, + { + "name": "a later key of a name replaces an earlier one", + "yaml": "a: 1\nb: 2\na: 3\n", + "expect": { + "a": "3", + "b": "2" + } + }, + { + "name": "two spellings of one number are one key: the later one stands", + "yaml": "8: a\n0o10: b\n0x8: c\n", + "expect": { + "8": "c" + } + }, + { + "name": "a tab is read as two spaces, as the Java engine reads a file: after a colon, as indentation", + "yaml": "a:\t1\nb:\n\tc: True\n\td:\n\t\te: 2.0\n", + "expect": { + "a": "1", + "b.c": "true", + "b.d.e": "2.0" + } + }, + { + "name": "the core schema has no merge key: << is a key like any other, and an alias is read as YAML reads it", + "yaml": "base: &base\n x: 1\n y: 2.5\nderived:\n <<: *base\n y: 3\ncopy: *base\n", + "expect": { + "base.x": "1", + "base.y": "2.5", + "derived.<<.x": "1", + "derived.<<.y": "2.5", + "derived.x": null, + "derived.y": "3", + "copy.x": "1", + "copy.y": "2.5" + } + }, + { + "name": "a %YAML 1.1 directive does not bring the older reading back", + "yaml": "%YAML 1.1\n---\na: yes\nb: 010\nc: 1_0\nd: 1:30\n", + "expect": { + "a": "yes", + "b": "10", + "c": "1_0", + "d": "1:30" + } + }, + { + "name": "a key named as something every object carries is a key like any other", + "yaml": "__proto__:\n x: 1\nconstructor: 2\ntoString: 3\n", + "expect": { + "__proto__.x": "1", + "constructor": "2", + "toString": "3" + } + } + ], + "reference_cases": [ + { + "name": "a reference sees the override of the key it names", + "file": "flag: false\nuses: ${flag:off}\ninside: 'is ${flag}'\n", + "overrides": { + "flag": "true" + }, + "expect": { + "flag": "true", + "uses": "true", + "inside": "is true" + }, + "kinds": { + "uses": "text" + } + }, + { + "name": "without an override, the file's value - as the value it is when the reference is the whole value", + "file": "flag: false\nuses: ${flag:off}\ninside: 'is ${flag}'\n", + "expect": { + "flag": "false", + "uses": "false", + "inside": "is false" + }, + "kinds": { + "uses": "boolean" + } + }, + { + "name": "an override names a key the file does not carry", + "file": "uses: ${only:none}\ninside: 'x-${only}'\n", + "overrides": { + "only": "o" + }, + "expect": { + "uses": "o", + "inside": "x-o" + } + }, + { + "name": "the environment variable wins over the override and the file", + "file": "MERCURY_VECTOR_NAME: file\nuses: ${MERCURY_VECTOR_NAME:none}\n", + "overrides": { + "MERCURY_VECTOR_NAME": "override" + }, + "env": { + "MERCURY_VECTOR_NAME": "environment" + }, + "expect": { + "uses": "environment", + "MERCURY_VECTOR_NAME": "override" + } + }, + { + "name": "the default when nothing carries the name; no value without a default", + "file": "uses: ${MERCURY_VECTOR_ABSENT:fallback}\nbare: ${MERCURY_VECTOR_ABSENT}\ninside: 'x-${MERCURY_VECTOR_ABSENT}-y'\ncolon: ${MERCURY_VECTOR_ABSENT:a:b}\n", + "unset": [ + "MERCURY_VECTOR_ABSENT" + ], + "expect": { + "uses": "fallback", + "bare": null, + "inside": "x--y", + "colon": "a:b" + } + }, + { + "name": "an override's own references are resolved, through the override of another key too", + "file": "b: 5\nuses: ${a}\n", + "overrides": { + "a": "${b}-${c:none}", + "c": "see" + }, + "expect": { + "a": "5-see", + "uses": "5-see" + } + }, + { + "name": "a referenced value inside a longer text is the text it reads as: a boolean, a float, a large integer", + "file": "flag: TRUE\nrate: 1.0\nbig: 12345678901234567890\nsmall: 1e-05\ninside: '${flag}/${rate}/${big}/${small}'\nwhole: ${rate}\n", + "expect": { + "inside": "true/1.0/12345678901234567890/1e-05", + "whole": "1.0" + }, + "kinds": { + "whole": "float" + } + }, + { + "name": "two keys that refer to each other: each ends at the other's default", + "file": "a: ${b:1}\nb: ${a:2}\n", + "expect": { + "a": "2", + "b": "1" + } + }, + { + "name": "a key that refers to itself has no value there: the default, or nothing", + "file": "a: ${a}\nb: ${b:d}\nc: 'x-${c}-y'\n", + "expect": { + "a": null, + "b": "d", + "c": "x--y" + } + }, + { + "name": "an override that refers to its own key takes its default, not the file's value", + "file": "port: 9000\n", + "overrides": { + "port": "${port:8080}" + }, + "expect": { + "port": "8080" + } + }, + { + "name": "a name every object carries is no environment variable and no key", + "file": "a: ${constructor:none}\nb: ${toString}\nc: ${__proto__:d}\nd: ${hasOwnProperty:e}\ne: 'x-${valueOf}-y'\n", + "unset": [ + "constructor", + "toString", + "__proto__", + "hasOwnProperty", + "valueOf" + ], + "expect": { + "a": "none", + "b": null, + "c": "d", + "d": "e", + "e": "x--y" + } + }, + { + "name": "a value its references leave empty is no value - the idiom for an optional setting - and an empty text written as one stays one", + "file": "effort: '${MERCURY_VECTOR_ABSENT:}'\nbare: ${MERCURY_VECTOR_ABSENT:}\ntwo: '${MERCURY_VECTOR_ABSENT:}${MERCURY_VECTOR_ABSENT:}'\nliteral: ''\naround: 'x${MERCURY_VECTOR_ABSENT:}'\n", + "unset": [ + "MERCURY_VECTOR_ABSENT" + ], + "expect": { + "effort": null, + "bare": null, + "two": null, + "literal": "", + "around": "x" + } + }, + { + "name": "a key its references leave empty reads as its default; an empty text written as one does not", + "file": "effort: '${MERCURY_VECTOR_ABSENT:}'\ntwo: '${MERCURY_VECTOR_ABSENT:}${MERCURY_VECTOR_ABSENT:}'\nliteral: ''\n", + "unset": [ + "MERCURY_VECTOR_ABSENT" + ], + "defaults": { + "effort": "medium", + "two": "dflt", + "literal": "dflt" + }, + "expect": { + "effort": "medium", + "two": "dflt", + "literal": "" + } + }, + { + "name": "a reference to a key its references leave empty takes its own default, else nothing", + "file": "inner: '${MERCURY_VECTOR_ABSENT:}'\nunset: ${MERCURY_VECTOR_ABSENT}\nuses: ${inner:fallback}\nbare: ${inner}\ninside: 'x-${inner}-y'\nthrough: ${unset:other}\n", + "unset": [ + "MERCURY_VECTOR_ABSENT" + ], + "expect": { + "inner": null, + "uses": "fallback", + "bare": null, + "inside": "x--y", + "through": "other" + } + }, + { + "name": "an environment variable that is set and empty leaves the value empty: no value, and the reference's own default is not taken", + "file": "uses: ${MERCURY_VECTOR_NAME:fallback}\ninside: 'x-${MERCURY_VECTOR_NAME:fallback}'\n", + "env": { + "MERCURY_VECTOR_NAME": "" + }, + "defaults": { + "uses": "dflt", + "inside": "dflt" + }, + "expect": { + "uses": "dflt", + "inside": "x-" + } + }, + { + "name": "an override its references leave empty is no value either, and does not uncover the file's", + "file": "a: text\n", + "overrides": { + "a": "${MERCURY_VECTOR_ABSENT:}" + }, + "unset": [ + "MERCURY_VECTOR_ABSENT" + ], + "defaults": { + "a": "dflt" + }, + "expect": { + "a": "dflt" + } + } + ], + "default_cases": [ + { + "name": "a key written without a value reads as a key that is not there: its default", + "file": "a:\nb: ~\nc: null\nd: ''\ne: text\n", + "defaults": { + "a": "dflt", + "b": "dflt", + "c": "dflt", + "d": "dflt", + "e": "dflt", + "f": "dflt" + }, + "expect": { + "a": "dflt", + "b": "dflt", + "c": "dflt", + "d": "", + "e": "text", + "f": "dflt" + } + }, + { + "name": "a reference to a key without a value takes its own default, else the default of the key that holds it", + "file": "empty:\nuses: ${empty:fallback}\nbare: ${empty}\ninside: 'x-${empty}-y'\n", + "defaults": { + "uses": "dflt", + "bare": "dflt", + "inside": "dflt" + }, + "expect": { + "uses": "fallback", + "bare": "dflt", + "inside": "x--y" + } + }, + { + "name": "an override with an empty value is an empty text, not the default", + "file": "a: text\n", + "overrides": { + "a": "" + }, + "defaults": { + "a": "dflt" + }, + "expect": { + "a": "" + } + } + ], + "whole_number_cases": [ + { + "value": 0, + "number": 0 + }, + { + "value": 1, + "number": 1 + }, + { + "value": 16000, + "number": 16000 + }, + { + "value": 16000.0, + "number": 16000 + }, + { + "value": 1000.0, + "number": 1000 + }, + { + "value": "16000", + "number": 16000 + }, + { + "value": " 16000 ", + "number": 16000 + }, + { + "value": "\t16000 ", + "number": 16000 + }, + { + "value": "  7

", + "number": 7 + }, + { + "value": "007", + "number": 7 + }, + { + "value": "0", + "number": 0 + }, + { + "value": 9007199254740991, + "number": 9007199254740991 + }, + { + "value": "9007199254740991", + "number": 9007199254740991 + }, + { + "value": "0000000000000000000000009007199254740991", + "number": 9007199254740991 + }, + { + "value": 9007199254740992, + "number": null + }, + { + "value": "9007199254740992", + "number": null + }, + { + "value": "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", + "number": null + }, + { + "value": 1.5, + "number": null + }, + { + "value": -5, + "number": null + }, + { + "value": -0.0, + "number": 0 + }, + { + "value": true, + "number": null + }, + { + "value": false, + "number": null + }, + { + "value": null, + "number": null + }, + { + "value": "", + "number": null + }, + { + "value": " ", + "number": null + }, + { + "value": "12 000", + "number": null + }, + { + "value": "16_000", + "number": null + }, + { + "value": "+5", + "number": null + }, + { + "value": "-5", + "number": null + }, + { + "value": "1e3", + "number": null + }, + { + "value": "16000.0", + "number": null + }, + { + "value": "0x10", + "number": null + }, + { + "value": "12abc", + "number": null + }, + { + "value": "٣", + "number": null + }, + { + "value": "12", + "number": null + }, + { + "value": "16000…", + "number": null + }, + { + "value": "16000", + "number": null + }, + { + "value": "16000\u001c", + "number": null + }, + { + "value": [ + 1 + ], + "number": null + }, + { + "value": { + "a": 1 + }, + "number": null + } + ], + "duration_cases": [ + { + "value": "30s", + "ms": 30000 + }, + { + "value": "2m", + "ms": 120000 + }, + { + "value": "1500ms", + "ms": 1500 + }, + { + "value": "1h", + "ms": 3600000 + }, + { + "value": "2d", + "ms": 172800000 + }, + { + "value": 30, + "ms": 30000 + }, + { + "value": 30.0, + "ms": 30000 + }, + { + "value": "30", + "ms": 30000 + }, + { + "value": "0", + "ms": 0 + }, + { + "value": "0ms", + "ms": 0 + }, + { + "value": 0, + "ms": 0 + }, + { + "value": " 5s ", + "ms": 5000 + }, + { + "value": "9007199254740991ms", + "ms": 9007199254740991 + }, + { + "value": "9007199254740s", + "ms": 9007199254740000 + }, + { + "value": "9007199254741s", + "ms": null + }, + { + "value": "9007199254740991s", + "ms": null + }, + { + "value": "5 s", + "ms": null + }, + { + "value": "5S", + "ms": null + }, + { + "value": "5sec", + "ms": null + }, + { + "value": "5 ms", + "ms": null + }, + { + "value": "1_0s", + "ms": null + }, + { + "value": "٣s", + "ms": null + }, + { + "value": "1.5s", + "ms": null + }, + { + "value": "0.5s", + "ms": null + }, + { + "value": 1.5, + "ms": null + }, + { + "value": "1e3", + "ms": null + }, + { + "value": "1e3ms", + "ms": null + }, + { + "value": "-5s", + "ms": null + }, + { + "value": "+5s", + "ms": null + }, + { + "value": -1, + "ms": null + }, + { + "value": "s", + "ms": null + }, + { + "value": "ms", + "ms": null + }, + { + "value": "", + "ms": null + }, + { + "value": true, + "ms": null + }, + { + "value": null, + "ms": null + }, + { + "value": "12abc", + "ms": null + } + ], + "switch_cases": [ + { + "value": true, + "default": false, + "switch": true + }, + { + "value": false, + "default": true, + "switch": false + }, + { + "value": "true", + "default": false, + "switch": true + }, + { + "value": "TRUE", + "default": false, + "switch": true + }, + { + "value": "tRuE", + "default": false, + "switch": true + }, + { + "value": "false", + "default": true, + "switch": false + }, + { + "value": "False", + "default": true, + "switch": false + }, + { + "value": null, + "default": false, + "switch": false + }, + { + "value": null, + "default": true, + "switch": true + }, + { + "value": "", + "default": false, + "switch": false + }, + { + "value": "", + "default": true, + "switch": true + }, + { + "value": "yes", + "default": false, + "switch": null + }, + { + "value": "on", + "default": true, + "switch": null + }, + { + "value": "no", + "default": true, + "switch": null + }, + { + "value": "off", + "default": false, + "switch": null + }, + { + "value": "1", + "default": false, + "switch": null + }, + { + "value": 1, + "default": false, + "switch": null + }, + { + "value": 0, + "default": true, + "switch": null + }, + { + "value": " true ", + "default": false, + "switch": null + }, + { + "value": "true\n", + "default": false, + "switch": null + }, + { + "value": "maybe", + "default": false, + "switch": null + }, + { + "value": [ + true + ], + "default": false, + "switch": null + }, + { + "value": { + "on": true + }, + "default": false, + "switch": null + } + ] +} diff --git a/tests/vectors/rest-automation-vectors.json b/tests/vectors/rest-automation-vectors.json index 0ee6efb..4f9d754 100644 --- a/tests/vectors/rest-automation-vectors.json +++ b/tests/vectors/rest-automation-vectors.json @@ -1,11 +1,12 @@ { "contract": "rest-automation", - "version": 3, - "description": "REST automation's shared vectors (RFC-0018 in mercury-composable): the pure half of the HTTP edge, run by mercury-python and mercury-nodejs against the same file. load_cases pin the rest.yaml parser - the entries, cors, headers and static-content blocks it accepts and the exact message of every refusal, the engines' messages plus the pack's own refusals of a flow binding, the HTTP relay and the A/B dual service; an upload entry is accepted and its files ride the request map (the engines' keys plus the bytes in contents, the pack's bounded form). A flag of an entry (tracing, stream, upload) is true or false as the Java engine reads it - the boolean, or the text in any letter case, which is what a ${NAME:default} reference resolves to; no value and an empty one are off; any other value is refused by name. timeout_cases pin the duration grammar and its clamp. match_cases pin the URL matching and its precedence over the 'basic' table (404 when no entry matches, 405 when the path matches under another method). header_transform_cases pin keep, drop and add. body_cases pin the request-body dispatch by content type, query_cases and cookie_cases the request parsing, negotiation_cases and stream_negotiation_cases the Accept rules, request_model_cases the AsyncHttpRequest map an edge builds and request_read_cases and upload_read_cases its accessors (file bytes travel as contents_base64 in this file), response_cases the mapping of a reply envelope to the status, header lines and body of the HTTP response, render_cases and stream_text_cases the payload rendering, error_body_cases the error shape. Header names are compared case-insensitively and header lines as a sorted list. No server is started by these cases; the edge is tested by each pack over HTTP.", + "version": 5, + "description": "REST automation's shared vectors (RFC-0018 in mercury-composable): the pure half of the HTTP edge, run by mercury-python and mercury-nodejs against the same file. load_cases pin the rest.yaml parser - the entries, cors, headers and static-content blocks it accepts and the exact message of every refusal, the engines' messages plus the pack's own refusals of a flow binding, the HTTP relay and the A/B dual service; an upload entry is accepted and its files ride the request map (the engines' keys plus the bytes in contents, the pack's bounded form). A flag of an entry (tracing, stream, upload) is true or false as the Java engine reads it - the boolean, or the text in any letter case, which is what a ${NAME:default} reference resolves to; no value and an empty one are off; any other value is refused by name. A rest.yaml is read as application.yml is, by the core schema of YAML 1.2.2: a boolean is true or false, also capitalized or in upper case - yes, no, on and off are text, so a flag written that way is refused - 1e3, 0x1E and 0o17 are numbers and 010 is ten, 1_0, 1:30 and 0b1010 are text, and a date is the text as written. timeout_cases pin an entry's timeout - a whole number of seconds or such a number and, right after it, one of ms, s, m, h, d, clamped to 1 s - 5 min - with ms null for a value that is no duration, which fails the load by name. match_cases pin the URL matching and its precedence over the 'basic' table (404 when no entry matches, 405 when the path matches under another method). header_transform_cases pin keep, drop and add. body_cases pin the request-body dispatch by content type, query_cases and cookie_cases the request parsing, negotiation_cases and stream_negotiation_cases the Accept rules, request_model_cases the AsyncHttpRequest map an edge builds and request_read_cases and upload_read_cases its accessors (file bytes travel as contents_base64 in this file), a name every object of the Node.js twin carries (__proto__, constructor, toString) being a name like any other in every map of a request and of a reply, upload_cases the pack's own reader of a multipart/form-data body - the files and the text fields it takes of a body (body as text, or body_base64 where it is not UTF-8) within a bound (16777216 when a case names none), a name or a filename in the extended form of RFC 5987 (name*, filename*) included, or the status and the message of its refusal - response_cases the mapping of a reply envelope to the status, header lines and body of the HTTP response, render_cases and stream_text_cases the payload rendering, error_body_cases the error shape. Header names are compared case-insensitively and header lines as a sorted list. No server is started by these cases; the edge is tested by each pack over HTTP.", "tables": { "basic": "rest:\n - service: \"greeting.api\"\n methods: ['GET']\n url: \"/api/greeting/{user}\"\n timeout: 10s\n cors: cors_1\n headers: header_1\n tracing: true\n - service: \"catch.all\"\n methods: ['GET', 'POST']\n url: \"/api/files/*\"\n - service: \"exact.match\"\n methods: ['GET']\n url: \"/api/greeting/system\"\n - service: \"version.ping\"\n methods: ['GET']\n url: \"/api/v*/ping\"\n - service: \"mid.any\"\n methods: ['GET']\n url: \"/api/mid/*/end\"\n - service: \"secure.api\"\n methods: ['POST']\n url: \"/api/secure\"\n authentication: \"api.key.check\"\n stream: true\n trace.id.header: 'X-Legacy-Trace'\n correlation.id.header: 'X-Legacy-Cid'\n traceparent.header: 'X-Trace-Context'\ncors:\n - id: cors_1\n options:\n - \"Access-Control-Allow-Origin: *\"\n - \"Access-Control-Allow-Methods: GET, POST, OPTIONS\"\n headers:\n - \"Access-Control-Allow-Origin: *\"\nheaders:\n - id: header_1\n request:\n drop: ['x-secret']\n response:\n add: [\"x-served-by: mercury\"]\nstatic-content:\n no-cache-pages: [\"/\", \"/index.html\", \"/app/*\"]\n filter:\n path: [\"/\", \"/assets/*\", \"*.html\"]\n exclusion: [\"*.css\"]\n service: \"http.request.filter\"\n", "defaults": "rest:\n - service: \"event.api.service\"\n methods: ['POST']\n url: \"/api/event\"\n timeout: 60s\n tracing: true\n - service: \"info.actuator.service\"\n methods: ['GET']\n url: \"/info\"\n timeout: 10s\n - service: \"routes.actuator.service\"\n methods: ['GET']\n url: \"/info/routes\"\n timeout: 10s\n - service: \"env.actuator.service\"\n methods: ['GET']\n url: \"/env\"\n timeout: 10s\n - service: \"health.actuator.service\"\n methods: ['GET']\n url: \"/health\"\n timeout: 30s\n - service: \"liveness.actuator.service\"\n methods: ['GET']\n url: \"/livenessprobe\"\n timeout: 10s\n", - "minimal": "rest:\n - service: x.y\n methods: ['get', 'Post']\n url: /a\n" + "minimal": "rest:\n - service: x.y\n methods: ['get', 'Post']\n url: /a\n", + "names": "rest:\n - service: \"names.api\"\n methods: ['GET']\n url: \"/names/{__proto__}/{constructor}/{toString}\"\n" }, "load_cases": [ { @@ -514,8 +515,8 @@ } }, { - "name": "the YAML 1.1 booleans turn a flag on and off: yes and on, no and off", - "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: yes\n stream: on\n upload: Yes\n - service: x.z\n methods: ['POST']\n url: /b\n tracing: no\n stream: off\n upload: OFF\n", + "name": "a boolean is true or false, also capitalized or in upper case", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: True\n stream: TRUE\n upload: true\n - service: x.z\n methods: ['POST']\n url: /b\n tracing: False\n stream: FALSE\n upload: false\n", "routes": [ { "service": "x.y", @@ -560,6 +561,26 @@ "filter": null } }, + { + "name": "yes is text, never a boolean - so a flag written that way is refused by name", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: yes\n", + "error": "rest[0] 'tracing' must be true or false" + }, + { + "name": "on is text, never a boolean - so a flag written that way is refused by name", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n stream: on\n", + "error": "rest[0] 'stream' must be true or false" + }, + { + "name": "no is text, in any letter case, never a boolean - so a flag written that way is refused by name", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n upload: No\n", + "error": "rest[0] 'upload' must be true or false" + }, + { + "name": "off is text, in any letter case, never a boolean - so a flag written that way is refused by name", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: OFF\n", + "error": "rest[0] 'tracing' must be true or false" + }, { "name": "a flag with no value, or an empty one, is off", "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing:\n stream: \"\"\n upload: ~\n", @@ -621,12 +642,12 @@ "error": "rest[0] 'tracing' must be true or false" }, { - "name": "the letter y is text, as PyYAML and SnakeYAML read it, never a boolean - so it is refused", + "name": "the letter y is text, never a boolean - so it is refused", "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: y\n", "error": "rest[0] 'tracing' must be true or false" }, { - "name": "the letter n is text, as PyYAML and SnakeYAML read it, never a boolean - so it is refused", + "name": "the letter n is text, never a boolean - so it is refused", "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n upload: n\n", "error": "rest[0] 'upload' must be true or false" }, @@ -644,6 +665,219 @@ "name": "an unknown cors id is found before a flag at fault", "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: maybe\n cors: nope\n", "error": "rest[0] unknown cors id 'nope'" + }, + { + "name": "a timeout that is no duration is refused by name", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: soon\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a timeout that is no duration is refused by name - a reference that did not resolve", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: ${TIMEOUT}\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a timeout that is no duration is refused by name - text with an underscore between its digits", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: '1_0s'\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a timeout that is no duration is refused by name - a fraction", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: 1.5\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a timeout that is no duration is refused by name - a boolean", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: true\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "the index tells which entry's timeout is at fault", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: 10s\n - service: x.z\n methods: ['GET']\n url: /b\n timeout: 10 s\n", + "error": "rest[1] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "an unknown headers id is found before a timeout at fault", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: soon\n headers: nope\n", + "error": "rest[0] unknown headers id 'nope'" + }, + { + "name": "a timeout at fault is found before a flag at fault", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: maybe\n timeout: soon\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a timeout with no value is the default; one with a unit the engines take is clamped as they clamp it", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout:\n - service: x.z\n methods: ['GET']\n url: /b\n timeout: 2h\n", + "routes": [ + { + "service": "x.y", + "methods": [ + "POST" + ], + "url": "/a", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + }, + { + "service": "x.z", + "methods": [ + "GET" + ], + "url": "/b", + "timeout_ms": 300000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + } + ], + "static": { + "no_cache_pages": [ + "/", + "/index.html" + ], + "filter": null + } + }, + { + "name": "the file is read by the core schema of YAML 1.2.2: 1e3 is a number, 0x1E is thirty, 0o17 is fifteen and 010 is ten", + "yaml": "rest:\n - service: x.s0\n methods: ['GET']\n url: /n0\n timeout: 1e3\n - service: x.s1\n methods: ['GET']\n url: /n1\n timeout: 0x1E\n - service: x.s2\n methods: ['GET']\n url: /n2\n timeout: 0o17\n - service: x.s3\n methods: ['GET']\n url: /n3\n timeout: 010\n", + "routes": [ + { + "service": "x.s0", + "methods": [ + "GET" + ], + "url": "/n0", + "timeout_ms": 300000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + }, + { + "service": "x.s1", + "methods": [ + "GET" + ], + "url": "/n1", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + }, + { + "service": "x.s2", + "methods": [ + "GET" + ], + "url": "/n2", + "timeout_ms": 15000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + }, + { + "service": "x.s3", + "methods": [ + "GET" + ], + "url": "/n3", + "timeout_ms": 10000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + } + ], + "static": { + "no_cache_pages": [ + "/", + "/index.html" + ], + "filter": null + } + }, + { + "name": "a number with an underscore between its digits is text in YAML 1.2.2, and no duration", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: 1_0\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a number in base 60 is text in YAML 1.2.2, and no duration", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: 1:30\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a number in base 2 is text in YAML 1.2.2, and no duration", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: 0b1010\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a date is the text as written", + "yaml": "rest:\n - service: 2026-11-30\n methods: ['GET']\n url: /a\n authentication: 2026-11-30T10:00:00Z\n", + "routes": [ + { + "service": "2026-11-30", + "methods": [ + "GET" + ], + "url": "/a", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": "2026-11-30T10:00:00Z", + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + } + ], + "static": { + "no_cache_pages": [ + "/", + "/index.html" + ], + "filter": null + } } ], "timeout_cases": [ @@ -667,13 +901,21 @@ "value": "0s", "ms": 1000 }, + { + "value": "0", + "ms": 1000 + }, { "value": "30m", "ms": 300000 }, { - "value": "garbage", - "ms": 30000 + "value": "1h", + "ms": 300000 + }, + { + "value": "1d", + "ms": 300000 }, { "value": null, @@ -684,16 +926,124 @@ "ms": 10000 }, { - "value": " 5 s ", + "value": "30", + "ms": 30000 + }, + { + "value": 30.0, + "ms": 30000 + }, + { + "value": 1000.0, + "ms": 300000 + }, + { + "value": " 5s ", + "ms": 5000 + }, + { + "value": "\t5s ", "ms": 5000 }, + { + "value": "9007199254740991ms", + "ms": 300000 + }, + { + "value": "garbage", + "ms": null + }, + { + "value": "", + "ms": null + }, + { + "value": " 5 s ", + "ms": null + }, + { + "value": "5 s", + "ms": null + }, + { + "value": "5S", + "ms": null + }, + { + "value": "5sec", + "ms": null + }, { "value": "-5s", - "ms": 30000 + "ms": null + }, + { + "value": "+5s", + "ms": null + }, + { + "value": -5, + "ms": null + }, + { + "value": "1_0s", + "ms": null + }, + { + "value": "٣s", + "ms": null + }, + { + "value": "10s", + "ms": null + }, + { + "value": "1e3", + "ms": null + }, + { + "value": "1.5s", + "ms": null + }, + { + "value": 10.5, + "ms": null + }, + { + "value": "5s…", + "ms": null + }, + { + "value": "5s", + "ms": null }, { "value": true, - "ms": 30000 + "ms": null + }, + { + "value": false, + "ms": null + }, + { + "value": [ + 30 + ], + "ms": null + }, + { + "value": { + "seconds": 30 + }, + "ms": null + }, + { + "value": 9007199254740992, + "ms": null + }, + { + "value": "9007199254740991s", + "ms": null } ], "match_cases": [ @@ -801,6 +1151,18 @@ "path": "/api/secure", "service": "secure.api", "params": {} + }, + { + "table": "names", + "name": "a path parameter named as something every object of the Node.js twin carries is a parameter like any other", + "method": "GET", + "path": "/names/one/two/three", + "service": "names.api", + "params": { + "__proto__": "one", + "constructor": "two", + "toString": "three" + } } ], "header_transform_cases": [ @@ -887,8 +1249,55 @@ "expect": { "accept": "*/*" } - } - ], + }, + { + "name": "a header named as something every object of the Node.js twin carries is dropped and added like any other", + "transform": { + "drop": [ + "toString" + ], + "add": [ + [ + "valueOf", + "v" + ], + [ + "__proto__", + "added" + ] + ] + }, + "headers": { + "__proto__": "p", + "constructor": "c", + "tostring": "t" + }, + "expect": { + "constructor": "c", + "valueOf": "v", + "__proto__": "added" + } + }, + { + "name": "a header named as something every object of the Node.js twin carries is kept like any other", + "transform": { + "keep": [ + "__PROTO__", + "Constructor" + ] + }, + "headers": { + "__proto__": "p", + "constructor": "c", + "tostring": "t", + "x-noise": "1" + }, + "expect": { + "__proto__": "p", + "constructor": "c" + } + } + ], "body_cases": [ { "name": "json object, charset ignored", @@ -989,6 +1398,33 @@ "body": "{\"a\":1}", "kind": "bytes", "value": "{\"a\":1}" + }, + { + "name": "a form field named as something every object of the Node.js twin carries is a field like any other", + "content_type": "application/x-www-form-urlencoded", + "body": "__proto__=p&constructor=c&toString=t&hasOwnProperty=h&valueOf=v&a=1", + "kind": "form", + "value": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v", + "a": "1" + } + }, + { + "name": "a JSON key named as something every object of the Node.js twin carries is a key like any other", + "content_type": "application/json", + "body": "{\"__proto__\": {\"x\": 1}, \"constructor\": \"c\", \"toString\": null}", + "kind": "value", + "value": { + "__proto__": { + "x": 1 + }, + "constructor": "c", + "toString": null + } } ], "query_cases": [ @@ -1041,6 +1477,31 @@ "c" ] } + }, + { + "query": "__proto__=p&constructor=c&toString=t&hasOwnProperty=h&valueOf=v&a=1", + "expect": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v", + "a": "1" + } + }, + { + "query": "constructor=c1&constructor=c2&__proto__=p1&__proto__=p2&__proto__=p3", + "expect": { + "constructor": [ + "c1", + "c2" + ], + "__proto__": [ + "p1", + "p2", + "p3" + ] + } } ], "cookie_cases": [ @@ -1068,6 +1529,17 @@ "expect": { "a": "b=c" } + }, + { + "header": "__proto__=p; constructor=c; toString=t; hasOwnProperty=h; valueOf=v; a=1", + "expect": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v", + "a": "1" + } } ], "negotiation_cases": [ @@ -1290,6 +1762,95 @@ "path": {} } } + }, + { + "name": "a header, a path and a query parameter, a cookie and a session key named as something every object of the Node.js twin carries", + "build": { + "method": "GET", + "url": "/x", + "headers": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "path": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "query": { + "__proto__": "p", + "constructor": [ + "c1", + "c2" + ], + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "cookies": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "session": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + } + }, + "map": { + "method": "GET", + "url": "/x", + "headers": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "cookies": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "session": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "parameters": { + "query": { + "__proto__": "p", + "constructor": [ + "c1", + "c2" + ], + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "path": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + } + } + } } ], "request_read_cases": [ @@ -1325,129 +1886,1052 @@ "user": "eric" } } - }, - "expect": { - "method": "GET", - "url": "/api/greeting/eric", - "path_parameter.user": "eric", - "query_parameter.q": "a", - "query_parameters.q": [ - "a", - "b" - ], - "query_parameter.lang": "fr", - "query_parameters.missing": [], - "header.accept": "*/*", - "header.ACCEPT": "*/*", - "cookie.first": "alpha", - "session_info.user": "demo", - "remote_ip": "127.0.0.1", - "is_secure": true, - "timeout_seconds": 10, - "query_string": "lang=fr&q=a&q=b", - "body": null + }, + "expect": { + "method": "GET", + "url": "/api/greeting/eric", + "path_parameter.user": "eric", + "query_parameter.q": "a", + "query_parameters.q": [ + "a", + "b" + ], + "query_parameter.lang": "fr", + "query_parameters.missing": [], + "header.accept": "*/*", + "header.ACCEPT": "*/*", + "cookie.first": "alpha", + "session_info.user": "demo", + "remote_ip": "127.0.0.1", + "is_secure": true, + "timeout_seconds": 10, + "query_string": "lang=fr&q=a&q=b", + "body": null + } + }, + { + "name": "x-ttl wins over the entry's timeout; defaults for what is absent", + "map": { + "headers": { + "x-ttl": "1500" + }, + "timeout": 10, + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "method": "GET", + "url": "/", + "timeout_seconds": 1, + "is_secure": false, + "path_parameter.user": null, + "query_parameter.q": null, + "header.accept": null, + "cookie.first": null, + "session_info.user": null, + "remote_ip": null, + "query_string": null, + "body": null + } + }, + { + "name": "an x-ttl that is no whole number leaves the entry's timeout - an underscore between digits", + "map": { + "headers": { + "x-ttl": "1_500" + }, + "timeout": 10, + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "timeout_seconds": 10 + } + }, + { + "name": "an x-ttl that is no whole number leaves the entry's timeout - a sign", + "map": { + "headers": { + "x-ttl": "+1500" + }, + "timeout": 10, + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "timeout_seconds": 10 + } + }, + { + "name": "an x-ttl that is no whole number leaves the entry's timeout - a digit of another script", + "map": { + "headers": { + "x-ttl": "١٥٠٠" + }, + "timeout": 10, + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "timeout_seconds": 10 + } + }, + { + "name": "an x-ttl with white space around its digits is that number", + "map": { + "headers": { + "x-ttl": " 2500 " + }, + "timeout": 10, + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "timeout_seconds": 2 + } + }, + { + "name": "the accessors read a name that is something every object of the Node.js twin carries as any other name", + "map": { + "headers": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "cookies": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "session": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "parameters": { + "query": { + "__proto__": "p", + "constructor": [ + "c1", + "c2" + ], + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "path": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + } + } + }, + "expect": { + "header.__proto__": "p", + "header.constructor": "c", + "header.TOSTRING": "t", + "cookie.__proto__": "p", + "cookie.constructor": "c", + "session_info.__proto__": "p", + "session_info.valueOf": "v", + "query_parameter.__proto__": "p", + "query_parameter.constructor": "c1", + "query_parameters.constructor": [ + "c1", + "c2" + ], + "query_parameters.__proto__": [ + "p" + ], + "path_parameter.__proto__": "p", + "path_parameter.hasOwnProperty": "h" + } + }, + { + "name": "a name every object of the Node.js twin carries, which a request does not hold, reads as any name it does not hold", + "map": { + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "header.constructor": null, + "header.__proto__": null, + "cookie.constructor": null, + "cookie.__proto__": null, + "session_info.valueOf": null, + "session_info.__proto__": null, + "query_parameter.constructor": null, + "query_parameter.__proto__": null, + "query_parameters.toString": [], + "query_parameters.__proto__": [], + "path_parameter.hasOwnProperty": null, + "path_parameter.__proto__": null + } + } + ], + "upload_read_cases": [ + { + "name": "the files of an upload through the accessors", + "map": { + "method": "POST", + "url": "/api/upload", + "filename": [ + "a.pdf", + "b.png" + ], + "file_type": [ + "application/pdf", + "image/png" + ], + "file_length": [ + 9, + 8 + ], + "size": 17, + "upload": [ + "doc", + "image" + ], + "contents_base64": [ + "JVBERi0xLjQg", + "iVBORw0KGgo=" + ], + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "is_file": true, + "content_length": 17, + "upload_tags": [ + "doc", + "image" + ], + "files": [ + { + "name": "a.pdf", + "content_type": "application/pdf", + "size": 9, + "tag": "doc", + "content_base64": "JVBERi0xLjQg" + }, + { + "name": "b.png", + "content_type": "image/png", + "size": 8, + "tag": "image", + "content_base64": "iVBORw0KGgo=" + } + ] + } + }, + { + "name": "no upload: no files, no size", + "map": { + "method": "GET", + "url": "/x", + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "is_file": false, + "content_length": null, + "upload_tags": [], + "files": [] + } + } + ], + "upload_cases": [ + { + "name": "a browser's form: text fields and a file with its type", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nQuarterly report\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\ncafé ☕\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"report.pdf\"\r\nContent-Type: application/pdf\r\n\r\n%PDF-1.4 data\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "report.pdf", + "content_type": "application/pdf", + "size": 13, + "tag": "doc", + "content_base64": "JVBERi0xLjQgZGF0YQ==" + } + ], + "fields": { + "title": "Quarterly report", + "note": "café ☕" + } + }, + { + "name": "a file's bytes are the bytes that arrived, line ends and all", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImltYWdlIjsgZmlsZW5hbWU9ImEucG5nIg0KQ29udGVudC1UeXBlOiBpbWFnZS9wbmcNCg0KiVBORw0KGgoA/w0KLS1YYk91TmRBcll4LS0NCg==", + "files": [ + { + "name": "a.png", + "content_type": "image/png", + "size": 10, + "tag": "image", + "content_base64": "iVBORw0KGgoA/w==" + } + ], + "fields": {} + }, + { + "name": "a file without a content type is application/octet-stream", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"notes.txt\"\r\n\r\nplain words\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "notes.txt", + "content_type": "application/octet-stream", + "size": 11, + "tag": "doc", + "content_base64": "cGxhaW4gd29yZHM=" + } + ], + "fields": {} + }, + { + "name": "a file input left empty is a file with an empty name and no bytes", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nnone attached\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "", + "content_type": "application/octet-stream", + "size": 0, + "tag": "doc", + "content_base64": "" + } + ], + "fields": { + "title": "none attached" + } + }, + { + "name": "a field named _charset_ is a field like any other, also when it comes first", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"_charset_\"\r\n\r\nutf-8\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\ncafé\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "_charset_": "utf-8", + "note": "café" + } + }, + { + "name": "a quote and the line ends in a field name and a filename arrive as %22, %0A and %0D", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a%22b%0D%0Ac\"\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"say %22hi%22.txt\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "say \"hi\".txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eQ==" + } + ], + "fields": { + "a\"b\r\nc": "x" + } + }, + { + "name": "no other percent sequence is unescaped, and a backslash is a backslash", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a%20b\"\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"C:\\dir\\my%2Ffile.txt\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "C:\\dir\\my%2Ffile.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eQ==" + } + ], + "fields": { + "a%20b": "x" + } + }, + { + "name": "a parameter value may be bare, up to the next semicolon", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=note\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=doc; filename=a.txt\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eQ==" + } + ], + "fields": { + "note": "x" + } + }, + { + "name": "blanks around the parameters, a trailing semicolon, parameters in any order and of any case", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\ncontent-disposition: FORM-DATA ; FileName=\"a.txt\" ;NAME=\"doc\" ; \r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eQ==" + } + ], + "fields": {} + }, + { + "name": "a parameter the reader does not know is passed over, and the first of a name stands", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; size=3; name=\"one\"; name=\"two\"\r\n\r\nabc\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "one": "abc" + } + }, + { + "name": "a header the reader does not know is passed over, and the first of a name stands", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nX-Custom: 1\r\nContent-Disposition: form-data; name=\"one\"\r\nContent-Disposition: form-data; name=\"two\"\r\n\r\nabc\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "one": "abc" + } + }, + { + "name": "a later field of a name replaces an earlier one", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"tag\"\r\n\r\nfirst\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"tag\"\r\n\r\nsecond\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "tag": "second" + } + }, + { + "name": "a field and a file named as something every object of the Node.js twin carries are a field and a file like any other", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"__proto__\"\r\n\r\np\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"constructor\"\r\n\r\nc\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"toString\"\r\n\r\nt\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"__proto__\"; filename=\"valueOf\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "valueOf", + "content_type": "application/octet-stream", + "size": 1, + "tag": "__proto__", + "content_base64": "eQ==" + } + ], + "fields": { + "__proto__": "p", + "constructor": "c", + "toString": "t" + } + }, + { + "name": "an empty name is taken: the field is named with the empty text, the file's tag is 'file'", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"\"\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"\"; filename=\"a.txt\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "file", + "content_base64": "eQ==" + } + ], + "fields": { + "": "x" + } + }, + { + "name": "a file's type is its Content-Type as written", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.bin\"\r\nContent-Type: Image/PNG; q=1 \r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a.bin", + "content_type": "Image/PNG; q=1", + "size": 1, + "tag": "doc", + "content_base64": "eQ==" + } + ], + "fields": {} + }, + { + "name": "a preamble before the first delimiter and an epilogue after the closing one are passed over", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "This is a preamble.\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--\r\nThis is an epilogue.\r\n--XbOuNdArYx\r\n", + "files": [], + "fields": { + "note": "x" + } + }, + { + "name": "blanks after a delimiter are passed over", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx \t\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--", + "files": [], + "fields": { + "note": "x" + } + }, + { + "name": "an upload without a part: the closing delimiter alone", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx--\r\n", + "files": [], + "fields": {} + }, + { + "name": "a field's content may hold line ends, dashes and another boundary", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\none\r\n--other\r\n\r\ntwo--\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "note": "one\r\n--other\r\n\r\ntwo--" + } + }, + { + "name": "a boundary in quotes, with the punctuation a boundary may hold", + "content_type": "multipart/form-data; boundary=\"a'()+_,-./:=? b\"", + "body": "--a'()+_,-./:=? b\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--a'()+_,-./:=? b--\r\n", + "files": [], + "fields": { + "note": "x" + } + }, + { + "name": "a boundary of seventy characters, after another parameter", + "content_type": "Multipart/Form-Data; charset=utf-8; BOUNDARY=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "body": "--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb--\r\n", + "files": [], + "fields": { + "note": "x" + } + }, + { + "name": "a field in UTF-8 keeps a byte order mark as the character it is", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "note": "x" + } + }, + { + "name": "a field may declare UTF-8, in any letter case, in quotes or bare", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a\"\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\ncafé\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"b\"\r\nContent-Type: text/plain; charset=\"utf8\"\r\n\r\ncafé\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "a": "café", + "b": "café" + } + }, + { + "name": "a field may declare ISO-8859-1 or US-ASCII", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImEiDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9SVNPLTg4NTktMQ0KDQpjYWbpDQotLVhiT3VOZEFyWXgNCkNvbnRlbnQtRGlzcG9zaXRpb246IGZvcm0tZGF0YTsgbmFtZT0iYiINCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbjsgY2hhcnNldD11cy1hc2NpaQ0KDQpwbGFpbg0KLS1YYk91TmRBcll4LS0NCg==", + "files": [], + "fields": { + "a": "café", + "b": "plain" + } + }, + { + "name": "a field in another charset is refused by the charset's name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\nContent-Type: text/plain; charset=Windows-1252\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes a text field in UTF-8, ISO-8859-1 or US-ASCII, not in 'Windows-1252'" + }, + { + "name": "a field that is not the UTF-8 it is taken for is refused by the field's name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9Im5vdGUiDQoNCmNhZukNCi0tWGJPdU5kQXJZeC0tDQo=", + "status": 400, + "error": "Upload text field 'note' is not UTF-8" + }, + { + "name": "a field that is not the US-ASCII it declares is refused by the field's name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9Im5vdGUiDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9VVMtQVNDSUkNCg0KY2Fm6Q0KLS1YYk91TmRBcll4LS0NCg==", + "status": 400, + "error": "Upload text field 'note' is not US-ASCII" + }, + { + "name": "a file is never read as text: bytes that are no UTF-8 pass", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImRvYyI7IGZpbGVuYW1lPSJhLnR4dCINCg0KY2Fm6Q0KLS1YYk91TmRBcll4LS0NCg==", + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 4, + "tag": "doc", + "content_base64": "Y2Fm6Q==" + } + ], + "fields": {} + }, + { + "name": "a transfer encoding that leaves the bytes as they are is taken: 7bit, 8bit, binary", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"b\"\r\ncontent-transfer-encoding: BINARY\r\n\r\ny\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\nz\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"c\"\r\nContent-Encoding: identity\r\n\r\nw\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eg==" + } + ], + "fields": { + "a": "x", + "b": "y", + "c": "w" + } + }, + { + "name": "a transfer encoding that changes the bytes is refused by name - base64", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\nContent-Transfer-Encoding: base64\r\n\r\naGVsbG8=\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes the bytes of a part as they are, not a Content-Transfer-Encoding of 'base64'" + }, + { + "name": "a transfer encoding that changes the bytes is refused by name - quoted-printable, on a file", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\nContent-Transfer-Encoding: Quoted-Printable\r\n\r\ncaf=E9\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes the bytes of a part as they are, not a Content-Transfer-Encoding of 'Quoted-Printable'" + }, + { + "name": "a content encoding is refused by name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.gz\"\r\nContent-Encoding: gzip\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes the bytes of a part as they are, not a Content-Encoding of 'gzip'" + }, + { + "name": "a part that is multipart itself is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"files\"\r\nContent-Type: multipart/mixed; boundary=inner\r\n\r\n--inner\r\n\r\nx\r\n--inner--\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes text fields and files, not a nested multipart part" + }, + { + "name": "a part that is multipart itself is refused, with no boundary of its own and ahead of a faulty disposition", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Type: Multipart/Mixed\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes text fields and files, not a nested multipart part" + }, + { + "name": "a part without a Content-Disposition is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Type: text/plain\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + }, + { + "name": "a part without a name is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; filename=\"a.txt\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + }, + { + "name": "a part that is not form-data is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: attachment; name=\"doc\"; filename=\"a.txt\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + }, + { + "name": "a filename in the extended form is taken: UTF-8, its bytes percent-encoded", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=UTF-8''caf%C3%A9%20%E4%B8%AD.txt\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "café 中.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eA==" + } + ], + "fields": {} + }, + { + "name": "the extended form wins over the plain parameter of its name, whichever comes first", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a\"; filename=\"plain.txt\"; filename*=UTF-8''star.txt\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"b\"; filename*=UTF-8''star.txt; filename=\"plain.txt\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "star.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "a", + "content_base64": "eA==" + }, + { + "name": "star.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "b", + "content_base64": "eQ==" + } + ], + "fields": {} + }, + { + "name": "a field's name in the extended form is taken too, alone or beside a plain one", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name*=UTF-8''caf%C3%A9\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"plain\"; name*=utf-8'en'd%C3%A9j%C3%A0\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "café": "x", + "déjà": "y" } }, { - "name": "x-ttl wins over the entry's timeout; defaults for what is absent", - "map": { - "headers": { - "x-ttl": "1500" + "name": "the extended form in ISO-8859-1, with a language, in any letter case and in quotes", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a\"; filename*=iso-8859-1'fr'caf%E9.txt\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"b\"; FileName*=\"Utf-8''in%20quotes.txt\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "café.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "a", + "content_base64": "eA==" }, - "timeout": 10, - "parameters": { - "query": {}, - "path": {} + { + "name": "in quotes.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "b", + "content_base64": "eQ==" } - }, - "expect": { - "method": "GET", - "url": "/", - "timeout_seconds": 1, - "is_secure": false, - "path_parameter.user": null, - "query_parameter.q": null, - "header.accept": null, - "cookie.first": null, - "session_info.user": null, - "remote_ip": null, - "query_string": null, - "body": null + ], + "fields": {} + }, + { + "name": "in the extended form a character that is not percent-encoded stands for itself, a plus sign and an apostrophe too, and nothing is unescaped twice", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a\"; filename*=UTF-8''a+b'c%25d.txt\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name*=UTF-8''q%2522r\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a+b'c%d.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "a", + "content_base64": "eA==" + } + ], + "fields": { + "q%22r": "y" } - } - ], - "upload_read_cases": [ + }, { - "name": "the files of an upload through the accessors", - "map": { - "method": "POST", - "url": "/api/upload", - "filename": [ - "a.pdf", - "b.png" - ], - "file_type": [ - "application/pdf", - "image/png" - ], - "file_length": [ - 9, - 8 - ], - "size": 17, - "upload": [ - "doc", - "image" - ], - "contents_base64": [ - "JVBERi0xLjQg", - "iVBORw0KGgo=" - ], - "parameters": { - "query": {}, - "path": {} + "name": "an empty filename in the extended form is a file with an empty name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=UTF-8''\r\n\r\n\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "", + "content_type": "application/octet-stream", + "size": 0, + "tag": "doc", + "content_base64": "" } - }, - "expect": { - "is_file": true, - "content_length": 17, - "upload_tags": [ - "doc", - "image" - ], - "files": [ - { - "name": "a.pdf", - "content_type": "application/pdf", - "size": 9, - "tag": "doc", - "content_base64": "JVBERi0xLjQg" - }, - { - "name": "b.png", - "content_type": "image/png", - "size": 8, - "tag": "image", - "content_base64": "iVBORw0KGgo=" - } - ] + ], + "fields": {} + }, + { + "name": "an extended parameter that is not charset'language'value is refused - no apostrophe", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=x.txt\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's filename* is not charset'language'value" + }, + { + "name": "an extended parameter that is not charset'language'value is refused - one apostrophe", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name*=UTF-8'x\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's name* is not charset'language'value" + }, + { + "name": "an extended parameter in another charset is refused by the charset's name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=Windows-1252''caf%E9.txt\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes a part's filename* in UTF-8 or ISO-8859-1, not in 'Windows-1252'" + }, + { + "name": "an extended parameter without a charset is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name*=''x\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes a part's name* in UTF-8 or ISO-8859-1, not in ''" + }, + { + "name": "a percent sign that two hexadecimal digits do not follow is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=UTF-8''bad%ZZ.txt\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's filename* holds a % that two hexadecimal digits do not follow" + }, + { + "name": "a percent sign that two hexadecimal digits do not follow is refused - at the end", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name*=UTF-8''cut%4\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's name* holds a % that two hexadecimal digits do not follow" + }, + { + "name": "an extended parameter whose bytes are not the charset it declares is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=UTF-8''caf%E9.txt\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload parameter filename* of a part is not UTF-8" + }, + { + "name": "an extended parameter whose bytes are not the charset it declares is refused - a sequence cut short", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name*=UTF-8''trunc%C3\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload parameter name* of a part is not UTF-8" + }, + { + "name": "a name at fault is told ahead of a filename at fault and of a part that is not form-data", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: attachment; name*=UTF-8''%FF; filename*=nope\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload parameter name* of a part is not UTF-8" + }, + { + "name": "a part that is not form-data is told ahead of a filename at fault", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: attachment; name=\"doc\"; filename*=nope\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + }, + { + "name": "a quote left open in a parameter is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's header parameters are malformed" + }, + { + "name": "a parameter without a value is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"; draft\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's header parameters are malformed" + }, + { + "name": "a malformed parameter of a field's content type is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\nContent-Type: text/plain; charset=\"utf-8\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's header parameters are malformed" + }, + { + "name": "a header line without a colon is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\nnot a header\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's header line is not 'name: value'" + }, + { + "name": "a header that is not UTF-8 is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImNhZukiDQoNCngNCi0tWGJPdU5kQXJZeC0tDQo=", + "status": 400, + "error": "Invalid multipart body - a part's headers are not UTF-8" + }, + { + "name": "a content type without a boundary is refused", + "content_type": "multipart/form-data", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - the content type declares no boundary" + }, + { + "name": "a boundary of more than seventy characters is refused", + "content_type": "multipart/form-data; boundary=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "body": "--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb--\r\n", + "status": 400, + "error": "Invalid multipart body - the content type declares no boundary" + }, + { + "name": "a boundary that ends with a space is refused", + "content_type": "multipart/form-data; boundary=\"a b \"", + "body": "--a b \r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--a b --\r\n", + "status": 400, + "error": "Invalid multipart body - the content type declares no boundary" + }, + { + "name": "a boundary with a character a boundary may not hold is refused", + "content_type": "multipart/form-data; boundary=\"a;b\"", + "body": "--a;b\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--a;b--\r\n", + "status": 400, + "error": "Invalid multipart body - the content type declares no boundary" + }, + { + "name": "a body with no delimiter is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "just text\r\n", + "status": 400, + "error": "Invalid multipart body - no part is delimited by the boundary the content type declares" + }, + { + "name": "an empty body is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "", + "status": 400, + "error": "Invalid multipart body - no part is delimited by the boundary the content type declares" + }, + { + "name": "a body delimited by another boundary than the one declared is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--other\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--other--\r\n", + "status": 400, + "error": "Invalid multipart body - no part is delimited by the boundary the content type declares" + }, + { + "name": "line ends that are not carriage return and line feed are refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\nContent-Disposition: form-data; name=\"note\"\n\nx\n--XbOuNdArYx--\n", + "status": 400, + "error": "Invalid multipart body - a delimiter is followed by neither a line end nor the closing dashes" + }, + { + "name": "a delimiter followed by other text is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYxxyz\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a delimiter is followed by neither a line end nor the closing dashes" + }, + { + "name": "a body that ends inside a part's headers is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"", + "status": 400, + "error": "Invalid multipart body - the closing delimiter is missing" + }, + { + "name": "a body that ends inside a part's content is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n", + "status": 400, + "error": "Invalid multipart body - the closing delimiter is missing" + }, + { + "name": "a part whose content has no line end before the next delimiter is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - the closing delimiter is missing" + }, + { + "name": "the parts' contents together may reach the bound: files and fields, counted in bytes", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\ncafé\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\n12345\r\n--XbOuNdArYx--\r\n", + "bound": 10, + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 5, + "tag": "doc", + "content_base64": "MTIzNDU=" + } + ], + "fields": { + "note": "café" } }, { - "name": "no upload: no files, no size", - "map": { - "method": "GET", - "url": "/x", - "parameters": { - "query": {}, - "path": {} + "name": "one byte more than the bound is a 413 - a field's bytes count, not its characters", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\ncafé\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\n123456\r\n--XbOuNdArYx--\r\n", + "bound": 10, + "status": 413, + "error": "Upload exceeds 10 bytes" + }, + { + "name": "the bound is told where it is passed, ahead of a later part at fault", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\n12345678901\r\n--XbOuNdArYx\r\nContent-Type: text/plain\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "bound": 10, + "status": 413, + "error": "Upload exceeds 10 bytes" + }, + { + "name": "a part at fault is told ahead of the bound a later part passes", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Type: text/plain\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\n12345678901\r\n--XbOuNdArYx--\r\n", + "bound": 10, + "status": 400, + "error": "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + }, + { + "name": "a bound of nothing takes no content at all", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "bound": 0, + "status": 413, + "error": "Upload exceeds 0 bytes" + }, + { + "name": "a bound of nothing takes parts without content", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\n\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"\"\r\n\r\n\r\n--XbOuNdArYx--\r\n", + "bound": 0, + "files": [ + { + "name": "", + "content_type": "application/octet-stream", + "size": 0, + "tag": "doc", + "content_base64": "" } - }, - "expect": { - "is_file": false, - "content_length": null, - "upload_tags": [], - "files": [] + ], + "fields": { + "note": "" } } ], @@ -1807,6 +3291,50 @@ ], "body": "too many" } + }, + { + "name": "a reply's key and a reply's header named as something every object of the Node.js twin carries are a key and a header like any other", + "status": 200, + "reply_headers": { + "__proto__": "p", + "constructor": "c" + }, + "body": { + "__proto__": { + "x": 1, + "y": null + }, + "constructor": "c", + "toString": null + }, + "accept": "application/json", + "head": false, + "transform": null, + "cors": null, + "cid": "cid-1", + "cid_header": "x-correlation-id", + "expect": { + "status": 200, + "headers": [ + [ + "__proto__", + "p" + ], + [ + "constructor", + "c" + ], + [ + "content-type", + "application/json" + ], + [ + "x-correlation-id", + "cid-1" + ] + ], + "body": "{\n \"__proto__\": {\n \"x\": 1\n },\n \"constructor\": \"c\"\n}" + } } ], "render_cases": [ From 42f7989b9525662827366c5c1f3c2b748eeb6dc9 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:00 -0800 Subject: [PATCH 2/5] fix(agent-tools): one reader of a URL and of robots.txt in both packs, a regex search that ends at a bound, settings by one rule The web tools take a URL apart by one set of rules, write it back in one form, refuse anything else by name and ask a site for exactly what was checked; a URL is at most 8192 characters. robots.txt is read by the tools' own RFC 9309 reader, a rule matched part by part between its stars, so its time is its length plus the path's. file.search with regex: true runs outside the host and ends at tools.file.search.timeout.ms with a 408; a literal is a substring test. A walk looks at 20,000 entries at most and says truncated. A tools.* setting that is no number or no switch stops the start by name. Co-Authored-By: Claude Fable 5.2 --- extensions/agent-tools/README.md | 59 +- extensions/agent-tools/agent_tools.py | 956 +++++++++++++---- .../agent-tools/resources/application.yml | 3 + tests/test_agent_tools.py | 975 +++++++++++++++++- 4 files changed, 1770 insertions(+), 223 deletions(-) diff --git a/extensions/agent-tools/README.md b/extensions/agent-tools/README.md index 2fb6839..2e7cbde 100644 --- a/extensions/agent-tools/README.md +++ b/extensions/agent-tools/README.md @@ -47,9 +47,9 @@ Without `tools.file.root` the file tools stay out (`File tools not registered - `tools.web.allow` the web tools stay out; without `tools.graph.uri` the graph tools stay out, and the two graph writers need `tools.graph.write=true` as well; `file.extract` registers with the file tools when the `documents` extra is installed; `time.now` registers unless `tools.time=false`. A root that is not a directory, an allowlist entry that is -not a host pattern, a graph URI that is not a Bolt URI or without the driver installed, or a limit that is not a number -stops the application by name. A graph database that does not answer at boot is logged, and its tools answer 503 until -it does. +not a host pattern, a graph URI that is not a Bolt URI or without the driver installed, a limit that is not a number +or a switch that is neither `true` nor `false` stops the application by name. A graph database that does not answer +at boot is logged, and its tools answer 503 until it does. ## The tools @@ -77,7 +77,19 @@ names folders only. Names are matched with their case. A symbolic link is an ent workspace and something is there - and a pattern never goes through it. A pattern that is absolute, holds `..` or names no entry is refused. A name is matched item by item, so the time a pattern takes is bounded by its length times the length of the path, however many stars it has, and the walk reads only the folders the pattern can still match -in. +in. A list or a search looks at 20 000 directory entries at most, whether they match or not, and says in `truncated` +that it stopped there. + +A search for a literal looks for it as a part of each line - of the line's lower-case form, the literal in lower case +too, unless `case_sensitive` is true - which takes a time bounded by the line's length. A search by regular +expression takes the expression as the runtime reads one (Python's `re` here, JavaScript's `RegExp` in the Node.js +twin) and never runs it in the host: a child interpreter - the one the application runs in, started isolated for the +search - compiles and runs it, the host stays responsive whatever the expression does, and the child is ended when +the search is over, and at `tools.file.search.timeout.ms` (10 s, counted from the start of the search) at the latest. +A search that has not finished by then is a 408 that names the key, and nothing is left running after it; an +expression the runtime cannot compile is a 400. The child costs a process start for each search by regular expression, +some tens of milliseconds; a literal starts none. A byte-order mark at the start of a file is no part of its text: +`file.read`, `file.search` and `file.extract` leave it out. `file.write` carries the write mark, so under the node's default mode a person approves it; the other file tools are reads and run unasked. @@ -98,6 +110,23 @@ shared address space (`100.64.0.0/10`). An IPv6 address is reached only inside t `tools.web.max.bytes` (1 MiB), the request at `tools.web.timeout.ms` (10 s), cookies are never kept, and the tool identifies itself as `Mercury-Composable-AgentTools/`. +**How a URL is read.** A URL - the `url` argument, the `Location` of a redirect, a link of a page - is taken apart by +the tools' own rules, the same in both packs, and written back in one form: a page is one page however its links +spell it, and what is asked of a site is what was checked. What a browser strips is stripped first: the controls and +the space at the ends, every tab and line break inside. The scheme is `http` or `https`, followed by two slashes, and +credentials are refused. The host is a name in letters, digits, hyphens, dots and underscores (an internationalized +name in its `xn--` form), written in lower case; or an IPv4 address in dotted decimal, four numbers from 0 to 255 +without leading zeros - a host whose last label spells a number any other way (`0177.0.0.1`, `2130706433`, `0x7f.1`, +`127.1`) is refused by name; or an IPv6 address in brackets, without a zone, written in its short form. The port is +the digits 0 to 9, from 1 to 65535, and is left out when it is the scheme's own. In the path and the query a +character a URI does not carry as it is - a space, a backslash, a letter outside ASCII - becomes its UTF-8 bytes +percent-encoded; an escape keeps its two digits in upper case, or becomes the letter, digit, hyphen, dot, underscore +or tilde it stands for; and the path loses its `.` and `..` segments. An empty path is `/`, an empty query is none, +and the fragment is dropped. An address longer than 8192 characters in that form is refused (`url is longer than +8192 characters`): a page may write a link of any length, and every link is asked of a `robots.txt` and of a +server. A link is read at the address of its page by the same rules, and one that names no web address +(`mailto:`, `javascript:`, another scheme) is not followed. + | Route | Row | Arguments | Result | | --- | --- | --- | --- | | `web.fetch` | `web_fetch` | `url` (required); `as`: `text` (default), `markdown`, `raw` | `{url, status, content_type, title, text, bytes, truncated}`; HTML is reduced to its readable text (scripts, styles, `nav`, `header` and `footer` dropped; headings, lists, code and links kept as text or as Markdown); a text resource (`text/*`, JSON, XML) is returned as is; `raw` returns the body as received; a binary response is a 400; the page's own status (a 404, a 500) is a result, not an error | @@ -108,6 +137,13 @@ include prefix and the delay are all limits, and a model that needs more asks ag by a small in-house parser (no dependency), enough for documentation and articles; an installation whose pages need main-content extraction may put a library behind the same route. +`robots.txt` is read by the tools' own reader, by RFC 9309, the same in both packs: the rules of the groups that name +`MercuryComposable`, in any letter case - or, when none does, of the groups for `*`; `Allow` and `Disallow`, with `*` +for any run of characters and a `$` at the end of a pattern for the end of the path, matched against the path and the +query in the form above; the longest pattern that matches decides, and `Allow` wins a tie. A site without a +`robots.txt`, or with one that cannot be read, allows all. A rule is matched part by part between its stars, so the +time it takes is bounded by its length plus the path's, however many stars it has. + ### The knowledge graph, inside one database The agent's own store for what it extracts - documents ingested once, their entities, relations and rules queried many @@ -182,6 +218,7 @@ time zone database (some containers) needs the `tzdata` package for any zone but | `tools.file.hidden` | `false` | expose hidden entries (a name starting with `.`) to the file tools | | `tools.file.write.extensions` | any | the suffixes `file.write` accepts, comma-separated (`.md, .txt`) | | `tools.file.line.max.chars` | `500` | the longest line `file.search` returns | +| `tools.file.search.timeout.ms` | `10000` | how long a search by regular expression may take, 100 ms at least; the search is ended there | | `tools.web.allow` | empty | the host patterns the web tools may reach, comma-separated: `docs.example.com`, `*.example.org`, `http://intranet.example`, `host:8443`; `*` is any run of characters and `[seq]` one character of a class (`[ab].example.com`), and brackets that hold an address are that address (`[::1]:8443`); empty, the web tools do not register | | `tools.web.allow.private` | `false` | allow addresses in loopback, private, link-local and multicast ranges | | `tools.web.max.bytes` | `1048576` | the most bytes read from one response | @@ -204,6 +241,13 @@ Limits are defaults a deployment lowers, never raises past the tool's caps (a `t logged and capped). The shipped `application.yml` takes the root and the allowlist from `${TOOLS_FILE_ROOT:}` and `${TOOLS_WEB_ALLOW:}`, so a deployment sets two environment variables or two `-D` flags. +A number and a switch are read the same way in both packs. A number is a number of the configuration with a whole +value, or a text of the digits 0 to 9 with white space around it at most, up to 9007199254740991; a time in +milliseconds is at most 2147483647 (about 24.8 days, the longest wait both packs' timers hold). A switch is the +configuration's `true` or `false`, or that word as text in any letter case. Any other value - a sign, an underscore, +an exponent, a decimal point in text, a digit of another script; `1` or `enabled` for a switch - stops the +application by name, and is never read as something near it. + ## The function contract | | | @@ -212,7 +256,7 @@ logged and capped). The shipped `application.yml` takes the root and the allowli | Reply | The result map of the table above. | | 400 | A refusal by rule: a path outside the workspace, a hidden entry, a binary file, a site that is not allowed, a private address, a bad argument, too many redirects, a response that is not text, a write clause in a read-only query, a deletion without the gate, an ingest with a bad label or a missing endpoint; or the graph database's own client error, by its code. The message names the rule and the key that governs it. | | 404 | The file or folder does not exist. | -| 408 | The site or the graph database did not answer within its timeout. | +| 408 | The site or the graph database did not answer within its timeout, or a search by regular expression did not finish within its own. | | 409 | `file.write` in `create` mode found the file. | | 502 | The host cannot be resolved, the connection failed, or the graph database failed in a way that is not the caller's. | | 503 | The graph database is not reachable or refused this process's credential. | @@ -304,5 +348,6 @@ the clause scan, the ingest plan, the error mapping on the driver's own exceptio a Word document generated in the test; the boot, the health route, the `describe` output and the catalog files complete the suite. The live graph test runs when `TOOLS_GRAPH_TEST_URI` names a database. -Four texts in the test file are the same, line for line, in the other pack's test file: the probes of the address -classification, the URL probes, and the tree and the probes of the glob grammar. A change to one goes into both. +Ten texts in the test file are the same, line for line, in the other pack's test file: the probes of the address +classification, the URL probes, the tree and the probes of the glob grammar, and the probes of a number, a switch, a +link, an allowlist entry, the reading of a URL and `robots.txt`. A change to one goes into both. diff --git a/extensions/agent-tools/agent_tools.py b/extensions/agent-tools/agent_tools.py index f103f44..123a86c 100644 --- a/extensions/agent-tools/agent_tools.py +++ b/extensions/agent-tools/agent_tools.py @@ -11,11 +11,12 @@ - ``tools.file.root`` names the one directory tree the four file tools may touch (``file.read``, ``file.write``, ``file.list``, ``file.search``). Every path is relative to it, resolved with - symbolic links followed, and refused when the result is outside the root. + symbolic links followed, and refused when the result is outside the root. A search by regular + expression runs in a child interpreter, ended at ``tools.file.search.timeout.ms``. - ``tools.web.allow`` names the host patterns the two web tools may reach (``web.fetch``, ``web.crawl``), over https unless a host is listed with ``http://``; an address in a loopback, private, link-local or multicast range is refused unless ``tools.web.allow.private=true``, and - every redirect is checked again. + every redirect is checked again. A URL is read by the tools' own rules, the same in both packs. - ``tools.graph.uri`` names the one graph database the four knowledge-graph tools reach over the Bolt protocol (``graph.schema``, ``graph.query`` in a read transaction; ``graph.write`` and ``graph.ingest`` only when ``tools.graph.write=true``, deletion only when ``tools.graph.delete=true``); @@ -46,6 +47,8 @@ import asyncio import base64 +import codecs +import contextlib import io import ipaddress import json @@ -53,20 +56,22 @@ import re import socket import stat +import subprocess import sys -import urllib.robotparser +import threading import zipfile from collections import deque -from collections.abc import Awaitable, Callable, Iterable, Sequence +from collections.abc import Awaitable, Callable, Generator, Sequence from dataclasses import dataclass from datetime import UTC, datetime from html.parser import HTMLParser from pathlib import Path, PurePosixPath, PureWindowsPath from typing import Any -from urllib.parse import SplitResult, urljoin, urlsplit, urlunsplit +from urllib.parse import SplitResult, urlsplit, urlunsplit from zoneinfo import ZoneInfo, ZoneInfoNotFoundError import aiohttp +from yarl import URL try: import neo4j @@ -108,18 +113,35 @@ # the token robots.txt rules are matched against ROBOTS_AGENT = "MercuryComposable" +# how a number is read, the same in both packs: the largest whole number both hold exactly +# (2**53 - 1) - above it the Node.js twin's numbers round, and the twins would read two different +# numbers from one value +MAX_WHOLE = 9007199254740991 +# the longest wait both packs' timers hold, in milliseconds (2**31 - 1, about 24.8 days): the +# Node.js twin's timers keep a delay in 32 bits with a sign and fire at once on a longer one +MAX_TIMER_MS = 2147483647 +# the white space ignored around a number, a switch and an entry of a list: the characters +# Python's str.strip() and JavaScript's trim() both take for white space, so neither pack +# accepts a character the other refuses +_BLANKS = "\t\n\x0b\x0c\r \xa0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000" +# a run of the digits 0 to 9: \d is those only under re.ASCII - without the flag it would let +# in the digits of every script +_DIGITS = re.compile(r"\d+", re.ASCII) + # files: the workspace and its limits FILE_ROOT = "tools.file.root" FILE_MAX_BYTES = "tools.file.max.bytes" FILE_HIDDEN = "tools.file.hidden" FILE_WRITE_EXTENSIONS = "tools.file.write.extensions" FILE_LINE_MAX_CHARS = "tools.file.line.max.chars" +FILE_SEARCH_TIMEOUT_MS = "tools.file.search.timeout.ms" DEFAULT_FILE_MAX_BYTES = 256 * 1024 DEFAULT_LINE_MAX_CHARS = 500 +DEFAULT_SEARCH_TIMEOUT_MS = 10000 LIST_DEFAULT, LIST_CAP = 200, 2000 SEARCH_DEFAULT, SEARCH_CAP = 100, 1000 CONTEXT_CAP = 3 -# how many directory entries a list or a search walks before it gives up - the tool's own bound +# how many directory entries a list or a search looks at before it gives up - the tool's own bound SCAN_LIMIT = 20000 WRITE_MODES = ("create", "overwrite", "append") @@ -586,21 +608,50 @@ def row_json(row: dict[str, Any]) -> str: # --- configuration helpers --------------------------------------------------------------------- +def _whole(digits: str) -> int | None: + """The whole number a run of ASCII digits spells, or None above MAX_WHOLE - told by the + count of its digits first, so a run of any length is judged without being converted.""" + significant = digits.lstrip("0") + if len(significant) > len(str(MAX_WHOLE)): + return None + number = int(significant or "0") + return number if number <= MAX_WHOLE else None + + +def _whole_number(value: Any) -> int | None: + """The whole number a value is: a number with a whole value - an integer, or a float, which + the Node.js twin cannot tell from one - or a text of ASCII digits with white space around + them at most. None for anything else: a boolean, a fraction, a sign, an exponent, a digit of + another script, a number beyond MAX_WHOLE.""" + if isinstance(value, str): + text = value.strip(_BLANKS) + return _whole(text) if _DIGITS.fullmatch(text) else None + if isinstance(value, float) and value.is_integer(): + value = int(value) + if isinstance(value, bool) or not isinstance(value, int) or abs(value) > MAX_WHOLE: + return None + return value + + def _setting(key: str, default: Any = None) -> Any: value = app_config().get(key, default) - if value is None or (isinstance(value, str) and not value.strip()): + if value is None or (isinstance(value, str) and not value.strip(_BLANKS)): return default return value -def _int_setting(key: str, default: int, *, floor: int = 1, cap: int | None = None) -> int: - raw = _setting(key, default) - try: - value = int(str(raw).strip()) - except ValueError as exc: - raise ToolsError(f"{key} must be an integer, not {raw!r}") from exc +def _int_setting( + key: str, default: int, *, floor: int = 1, cap: int | None = None, most: int = MAX_WHOLE +) -> int: + """A setting that is a whole number, inside its bounds: under the floor or over the most it + stops the boot by name, over the tool's cap it is lowered to the cap with a warning.""" + value = _whole_number(_setting(key, default)) + if value is None: + raise ToolsError(f"{key} must be an integer") if value < floor: raise ToolsError(f"{key} must be at least {floor}") + if value > most: + raise ToolsError(f"{key} must be at most {most}") if cap is not None and value > cap: log.warning( "%s=%d is over the tool's cap %d - a deployment lowers a limit, never raises it; using %d", @@ -614,15 +665,15 @@ def _int_setting(key: str, default: int, *, floor: int = 1, cap: int | None = No def _bool_setting(key: str, default: bool) -> bool: + """A setting that is a switch: true or false, the boolean or the text in any letter case. + Any other value stops the boot by name - it is never read as on or as off.""" raw = _setting(key, default) if isinstance(raw, bool): return raw - text = str(raw).strip().lower() - if text in ("true", "yes", "on", "1"): - return True - if text in ("false", "no", "off", "0"): - return False - raise ToolsError(f"{key} must be true or false, not {raw!r}") + text = raw.strip(_BLANKS).lower() if isinstance(raw, str) else "" + if text not in ("true", "false"): + raise ToolsError(f"{key} must be true or false") + return text == "true" def _list_setting(key: str) -> tuple[str, ...]: @@ -630,7 +681,7 @@ def _list_setting(key: str) -> tuple[str, ...]: if raw is None: return () items = raw if isinstance(raw, (list, tuple)) else str(raw).split(",") - return tuple(str(item).strip() for item in items if str(item).strip()) + return tuple(str(item).strip(_BLANKS) for item in items if str(item).strip(_BLANKS)) # --- argument helpers - a tool's body is a map of the row's properties ------------------------ @@ -667,9 +718,10 @@ def _integer(args: dict[str, Any], name: str, *, default: int, floor: int, cap: value = args.get(name) if value is None: return min(default, cap) - if isinstance(value, bool) or not isinstance(value, (int, float)) or int(value) != value: + # the row says integer: a number with a whole value, never a text of digits + number = None if isinstance(value, str) else _whole_number(value) + if number is None: raise AppException(400, f"{name} must be an integer") - number = int(value) if number < floor: raise AppException(400, f"{name} must be at least {floor}") return min(number, cap) @@ -704,6 +756,7 @@ class FileSandbox: write_extensions: tuple[str, ...] = () line_max_chars: int = DEFAULT_LINE_MAX_CHARS extract_max_chars: int = DEFAULT_EXTRACT_MAX_CHARS + search_timeout_ms: int = DEFAULT_SEARCH_TIMEOUT_MS def load_file_sandbox() -> FileSandbox | None: @@ -728,6 +781,12 @@ def load_file_sandbox() -> FileSandbox | None: extract_max_chars=_int_setting( FILE_EXTRACT_MAX_CHARS, DEFAULT_EXTRACT_MAX_CHARS, floor=100 ), + search_timeout_ms=_int_setting( + FILE_SEARCH_TIMEOUT_MS, + DEFAULT_SEARCH_TIMEOUT_MS, + floor=MIN_WEB_TIMEOUT_MS, + most=MAX_TIMER_MS, + ), ) @@ -765,17 +824,23 @@ def binary_kind(head: bytes) -> str | None: return "binary" if b"\x00" in head else None +def _without_mark(text: str) -> str: + """A text without the byte-order mark at its start: the mark says how a file is encoded and + is no part of what it says.""" + return text.removeprefix("\ufeff") + + def decode_utf8(data: bytes, *, truncated: bool) -> str | None: - """The bytes as UTF-8, or ``None`` when they are not; a cut that split a multi-byte character - is forgiven at the tail.""" + """The bytes as UTF-8, without a byte-order mark at their start, or ``None`` when they are + not UTF-8; a cut that split a multi-byte character is forgiven at the tail.""" try: - return data.decode("utf-8") + return _without_mark(data.decode("utf-8")) except UnicodeDecodeError: if not truncated: return None for trim in range(1, 4): try: - return data[:-trim].decode("utf-8") + return _without_mark(data[:-trim].decode("utf-8")) except UnicodeDecodeError: continue return None @@ -967,48 +1032,194 @@ def _scan_entry( glob: Glob, found: list[Path], queue: deque[tuple[str, str, int]], -) -> bool: +) -> None: """One entry of a walk, in the directory the walk is at: it joins ``found`` when the glob - matches it, and the queue when it is a directory the glob reaches into. True when the scan - limit is passed.""" + matches it, and the queue when it is a directory the glob reaches into.""" _directory, relative_dir, level = here relative = f"{relative_dir}/{entry.name}" if relative_dir else entry.name if glob.test(relative): found.append(Path(entry.path)) - if len(found) > SCAN_LIMIT: - return True if _is_folder(entry) and glob.enters(entry.name, level): queue.append((entry.path, relative, level + 1)) - return False -def _glob_walk(base: Path, glob: Glob) -> list[Path]: - """Every entry under a directory that matches a compiled glob, bounded by the scan limit; a - symbolic link is an entry, never descended into.""" +def _entries_of(directory: str) -> Generator[os.DirEntry[str], None, None]: + """The entries of a directory of a walk, one at a time; none for one that cannot be read.""" + try: + with os.scandir(directory) as listing: + yield from listing + except OSError: + return + + +def _glob_walk(base: Path, glob: Glob) -> tuple[list[Path], bool]: + """Every entry under a directory that matches a compiled glob, and whether the walk was + cut: it looks at SCAN_LIMIT entries at most, whether they match or not. A symbolic link is + an entry, never descended into.""" found: list[Path] = [] + looked = 0 queue: deque[tuple[str, str, int]] = deque([(str(base), "", 1)]) - while queue and len(found) <= SCAN_LIMIT: + while queue: here = queue.popleft() - try: - with os.scandir(here[0]) as listing: - entries = list(listing) - except OSError: - continue - for entry in entries: - if _scan_entry(entry, here, glob, found, queue): + with contextlib.closing(_entries_of(here[0])) as listing: + for entry in listing: + if looked >= SCAN_LIMIT: + return found, True + looked += 1 + _scan_entry(entry, here, glob, found, queue) + return found, False + + +def _listing(base: Path) -> tuple[list[Path], bool]: + """The direct entries of a directory, SCAN_LIMIT of them at most, and whether one was left.""" + found: list[Path] = [] + with os.scandir(base) as listing: + for entry in listing: + if len(found) >= SCAN_LIMIT: + return found, True + found.append(Path(entry.path)) + return found, False + + +# What the child interpreter of a search by regular expression runs. It compiles the expression +# it is sent and says whether it could; then it answers each block of lines - how many matches +# are wanted at most and the lines, joined by line feeds - with the numbers of the lines that +# match. Should its host be gone, it ends itself a second after the bound, whatever it is doing. +_SEARCH_CHILD = r""" +import faulthandler, json, os, re, sys +receive, send = sys.stdin.buffer, sys.stdout.buffer +head = json.loads(receive.readline()) +unseen = open(os.devnull, "w") +faulthandler.dump_traceback_later(head["bound"], exit=True, file=unseen) +try: + matcher = re.compile(head["pattern"], head["flags"]) +except (re.error, OverflowError, RecursionError) as failure: + send.write(b"!" + json.dumps(str(failure)).encode() + b"\n") + sys.exit() +send.write(b"\n") +send.flush() +for size in iter(receive.readline, b""): + most, length = map(int, size.split()) + hits = [] + for number, line in enumerate(receive.read(length).decode().split("\n")): + if matcher.search(line): + hits.append(str(number)) + if len(hits) >= most: break - return found + send.write(" ".join(hits).encode() + b"\n") + send.flush() +""" -def _search_matcher(pattern: str, *, regex: bool, case_sensitive: bool) -> re.Pattern[str]: - """The pattern of a search, compiled: a literal unless it is a regular expression, any case - unless the search is case-sensitive.""" - try: - return re.compile( - pattern if regex else re.escape(pattern), 0 if case_sensitive else re.IGNORECASE +class _LiteralSearch: + """A search for a literal, made in the host: a line holds the literal when the literal is a + part of it - of its lower-case form, for a search that ignores case. That takes a time + bounded by the line's length, so a literal needs no child.""" + + def __init__(self, pattern: str, *, case_sensitive: bool): + self._needle = pattern if case_sensitive else pattern.lower() + self._case_sensitive = case_sensitive + + def hits(self, lines: list[str], most: int) -> list[int]: + """The numbers of the lines the literal is in, counted from 0, so many at most.""" + found: list[int] = [] + for number, line in enumerate(lines): + if self._needle in (line if self._case_sensitive else line.lower()): + found.append(number) + if len(found) >= most: + break + return found + + def close(self) -> None: + """Nothing to end: the search ran in the host.""" + + +class _ExpressionSearch: + """A search by regular expression, made in a child interpreter: the host never compiles or + runs the model's expression, so it stays responsive whatever the expression does. The child + is ended at the bound, counted from the start of the search, and at the end of the search + at the latest - nothing is left running after it.""" + + def __init__(self, pattern: str, *, case_sensitive: bool, timeout_ms: int): + self._timeout_ms = timeout_ms + self._bound_passed = threading.Event() + # the interpreter this process runs in, isolated from the environment and the site + self._child = subprocess.Popen( + [sys.executable, "-I", "-S", "-c", _SEARCH_CHILD], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, ) - except re.error as exc: - raise AppException(400, f"pattern is not a valid regular expression ({exc})") from exc + self._timer = threading.Timer(timeout_ms / 1000, self._end_at_the_bound) + self._timer.daemon = True + self._timer.start() + head = { + "pattern": pattern, + "flags": 0 if case_sensitive else int(re.IGNORECASE), + "bound": timeout_ms / 1000 + 1, + } + try: + verdict = self._ask(json.dumps(head).encode() + b"\n") + except BaseException: + self.close() + raise + if verdict: + self.close() + reason = json.loads(verdict[1:]) + raise AppException(400, f"pattern is not a valid regular expression ({reason})") + + def _end_at_the_bound(self) -> None: + self._bound_passed.set() + self._child.kill() + + def _ask(self, request: bytes) -> bytes: + """One request to the child and the line it answers with, without its line feed. A child + that was ended at the bound answers nothing, which is the bound's refusal.""" + send, receive = self._child.stdin, self._child.stdout + assert send is not None + assert receive is not None + try: + send.write(request) + send.flush() + answer = receive.readline() + except OSError: # the pipe of a child that is gone + answer = b"" + if answer.endswith(b"\n"): + return answer[:-1] + if self._bound_passed.is_set(): + raise AppException( + 408, + f"the search did not finish within {self._timeout_ms} ms " + f"({FILE_SEARCH_TIMEOUT_MS}) - a simpler regular expression, or a narrower " + f"path or glob, finishes sooner", + ) + raise AppException(500, "the search by regular expression ended before it answered") + + def hits(self, lines: list[str], most: int) -> list[int]: + if not lines: + return [] + block = "\n".join(lines).encode() + answer = self._ask(f"{most} {len(block)}\n".encode() + block) + return [int(number) for number in answer.split()] + + def close(self) -> None: + """End the child at once, whether it has finished or not, and wait until it is gone.""" + self._timer.cancel() + self._child.kill() + for pipe in (self._child.stdin, self._child.stdout): + if pipe is not None: + with contextlib.suppress(OSError): + pipe.close() + self._child.wait() + + +def _line_search( + pattern: str, *, regex: bool, case_sensitive: bool, timeout_ms: int +) -> _LiteralSearch | _ExpressionSearch: + """What finds the lines a pattern is in: a literal in the host, a regular expression in a + child that can be ended.""" + if regex: + return _ExpressionSearch(pattern, case_sensitive=case_sensitive, timeout_ms=timeout_ms) + return _LiteralSearch(pattern, case_sensitive=case_sensitive) def _text_bytes(resolved: Path) -> bytes | None: @@ -1028,8 +1239,9 @@ def _text_bytes(resolved: Path) -> bytes | None: def _lines_of(data: bytes) -> list[str]: - """The lines of a text file; the newline that ends the file starts no line.""" - lines = _LINE_END.split(data.decode("utf-8", errors="replace")) + """The lines of a text file, without a byte-order mark at its start; the newline that ends + the file starts no line.""" + lines = _LINE_END.split(_without_mark(data.decode("utf-8", errors="replace"))) if lines[-1] == "": lines.pop() return lines @@ -1037,7 +1249,7 @@ def _lines_of(data: bytes) -> list[str]: def _match_lines( lines: list[str], - matcher: re.Pattern[str], + hits: list[int], shown: str, matches: list[dict[str, Any]], *, @@ -1045,18 +1257,17 @@ def _match_lines( width: int, limit: int, ) -> bool: - """The lines of one file that match, added to the matches with the lines around them, each - cut to the width; True when a match was left out because the result is full.""" - for index, line in enumerate(lines): - if not matcher.search(line): - continue + """The lines of one file that match - the ones the hits number, from 0 - added to the + matches with the lines around them, each cut to the width; True when a match was left out + because the result is full.""" + for index in hits: if len(matches) >= limit: return True matches.append( { "path": shown, "line": index + 1, - "text": line[:width], + "text": lines[index][:width], "before": [text[:width] for text in lines[max(0, index - context) : index]], "after": [text[:width] for text in lines[index + 1 : index + 1 + context]], } @@ -1137,21 +1348,17 @@ def _walk( ) -> tuple[list[tuple[str, Path, os.stat_result]], bool]: """The entries under a directory, sorted by their workspace-relative path, each with its real path and what it is; hidden entries, entries that escape the workspace and entries - that are gone are left out. The second value says the walk hit the scan bound.""" + that are gone are left out. The second value says the walk was cut at the scan bound: + it had looked at SCAN_LIMIT entries and there were more.""" folders_only = False - candidates: Iterable[Path] if pattern: glob = compile_glob(pattern) folders_only = glob.folders_only - candidates = _glob_walk(base, glob) + candidates, bounded = _glob_walk(base, glob) else: - candidates = base.iterdir() + candidates, bounded = _listing(base) found: list[tuple[str, Path, os.stat_result]] = [] - bounded = False for entry in candidates: - if len(found) >= SCAN_LIMIT: - bounded = True - break exposed = self._exposed_entry(entry, files_only=files_only, folders_only=folders_only) if exposed is not None: found.append(exposed) @@ -1272,32 +1479,35 @@ def search(self, _headers: dict[str, str], body: Body) -> Any: max_results = _integer(args, "max_results", default=SEARCH_DEFAULT, floor=1, cap=SEARCH_CAP) if not pattern: raise AppException(400, "pattern must not be empty") - matcher = _search_matcher(pattern, regex=regex, case_sensitive=case_sensitive) - base = self._directory(path) - found, bounded = self._walk(base, file_glob, files_only=True) - width = self.sandbox.line_max_chars - matches: list[dict[str, Any]] = [] - searched = 0 - truncated = bounded - for shown, resolved, _info in found: - if truncated and len(matches) >= max_results: - break - data = _text_bytes(resolved) - if data is None: - continue - searched += 1 - if _match_lines( - _lines_of(data), - matcher, - shown, - matches, - context=context, - width=width, - limit=max_results, - ): - truncated = True - if truncated and len(matches) >= max_results: - break + search = _line_search( + pattern, + regex=regex, + case_sensitive=case_sensitive, + timeout_ms=self.sandbox.search_timeout_ms, + ) + with contextlib.closing(search): + base = self._directory(path) + found, bounded = self._walk(base, file_glob, files_only=True) + width = self.sandbox.line_max_chars + matches: list[dict[str, Any]] = [] + searched = 0 + truncated = bounded + for shown, resolved, _info in found: + if truncated and len(matches) >= max_results: + break + data = _text_bytes(resolved) + if data is None: + continue + searched += 1 + lines = _lines_of(data) + # one match more than the result has room for says that the result was cut + hits = search.hits(lines, max_results - len(matches) + 1) + if _match_lines( + lines, hits, shown, matches, context=context, width=width, limit=max_results + ): + truncated = True + if truncated and len(matches) >= max_results: + break log.info( "file.search 200 %d matches in %d files%s", len(matches), @@ -1339,7 +1549,7 @@ def extract(self, _headers: dict[str, str], body: Body) -> Any: elif kind == "docx": pages = [_docx_text(data, relative)] elif kind == "html": - pages = [html_to_text(data.decode("utf-8", errors="replace"))[1]] + pages = [html_to_text(_without_mark(data.decode("utf-8", errors="replace")))[1]] else: text = decode_utf8(data, truncated=False) if text is None: @@ -1400,22 +1610,14 @@ def document_kind(data: bytes, suffix: str) -> str | None: _PAGE_SPAN = re.compile(r"(\d+)(?:-(\d+))?", re.ASCII) -def _page_number(digits: str) -> int: - """A run of digits as a page number; a run too long for the integer reader is a page beyond - any document.""" - try: - return int(digits) - except ValueError: - return sys.maxsize - - def _page_span(part: str) -> tuple[int, int]: - """``7`` or ``1-3`` to the first and the last page number it names, counted from 1.""" + """``7`` or ``1-3`` to the first and the last page number it names, counted from 1. A page + number is a whole number as both packs read one, MAX_WHOLE at most.""" match = _PAGE_SPAN.fullmatch(part) - if match is None: + start = _whole(match.group(1)) if match else None + end = start if match is None or match.group(2) is None else _whole(match.group(2)) + if start is None or end is None: raise AppException(400, "pages must be page numbers and ranges such as 1-3,7") - start = _page_number(match.group(1)) - end = start if match.group(2) is None else _page_number(match.group(2)) if start < 1 or end < start: raise AppException( 400, "pages must be page numbers and ranges such as 1-3,7, counted from 1" @@ -1428,11 +1630,11 @@ def page_range(spec: str | None, total: int) -> list[int]: an empty selection means every page.""" if total <= 0: return [] - if spec is None or not spec.strip(): + if spec is None or not spec.strip(_BLANKS): return list(range(1, total + 1)) wanted: list[int] = [] for token in spec.split(","): - part = token.strip() + part = token.strip(_BLANKS) if not part: continue start, end = _page_span(part) @@ -1483,6 +1685,270 @@ def _docx_text(data: bytes, relative: str) -> str: ) from exc +# --- how a web address is read: the same in both packs ------------------------------------------- +# +# A URL - the url argument, the Location of a redirect, a link of a page - is taken apart by the +# rules below and written back in one form, so both packs take the same text for the same address, +# compare it and ask for it in the same words, and neither depends on its runtime's own reader: +# +# - what a browser strips is stripped first: the controls and the space at the ends, and every tab +# and line break inside; +# - the scheme is http or https, in any letter case, followed by two slashes; +# - no credentials; the host is a name in letters, digits, hyphens, dots and underscores, written +# in lower case, or an IPv4 address in dotted decimal - four numbers from 0 to 255 without leading +# zeros, and no other spelling of a number - or an IPv6 address in brackets, without a zone, +# written in its one short form; the port is ASCII digits from 1 to 65535, left out when it is +# the scheme's own; +# - in the path and the query a character a URI does not carry as it is becomes its UTF-8 bytes +# percent-encoded, an escape keeps its two digits in upper case - or becomes the letter, digit, +# hyphen, dot, underscore or tilde it stands for - and the path loses its . and .. segments; +# - an empty path is /, an empty query is none, and the fragment is no part of the address; +# - an address longer than 8192 characters in that form is refused. + +_DEFAULT_PORTS = {"http": 80, "https": 443} +# what a URL is told when it is no http(s) address, or none the reader can take apart +_NOT_A_WEB_ADDRESS = "url must start with https:// (or http:// for a host listed with it)" +_INVALID_PORT = "url has an invalid port" +_INVALID_HOST = ( + "url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores)" +) +_NOT_DOTTED_DECIMAL = ( + "is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros)" +) +# the longest address the tools take, counted in its one form: about what a server's request line +# holds. A page may write a link of any length, and a robots.txt is asked about every one of them +MAX_URL_LENGTH = 8192 +_TOO_LONG = f"url is longer than {MAX_URL_LENGTH} characters" +# what a browser strips from the ends of a URL - the controls and the space - and from all of it +_C0_OR_SPACE = "".join(chr(code) for code in range(0x21)) +_TAB_OR_LINE_BREAK = str.maketrans("", "", "\t\n\r") +_SCHEME = re.compile(r"([A-Za-z][A-Za-z0-9+.-]*):") +_HOST_NAME = re.compile(r"[A-Za-z0-9._-]+") +# a host whose last label spells a number - digits, or 0x and hexadecimal digits - is an address; +# \d is the digits 0 to 9 only under re.ASCII +_NUMBER_LABEL = re.compile(r"(?:^|\.)(?:\d+|0x[0-9a-f]*)$", re.ASCII) +_DOTTED_DECIMAL = re.compile(r"(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}", re.ASCII) +# what an address is rewritten at: an escape, and a character a URI does not carry as it is +_REWRITTEN = re.compile(r"%[0-9A-Fa-f]{2}|[^A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=]") +_UNRESERVED = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") + + +def _stripped(text: str) -> str: + """A URL without what a browser strips before it reads one.""" + return text.strip(_C0_OR_SPACE).translate(_TAB_OR_LINE_BREAK) + + +def _rewritten(found: re.Match[str]) -> str: + """An escape in its one form - the character itself when a URI never needs it escaped, else + its two digits in upper case - and any other character as its UTF-8 bytes, percent-encoded; + half of a surrogate pair is the replacement character.""" + text = found.group() + if len(text) == 3: + char = chr(int(text[1:], 16)) + return char if char in _UNRESERVED else text.upper() + data = ("\ufffd" if "\ud800" <= text <= "\udfff" else text).encode() + return "".join(f"%{byte:02X}" for byte in data) + + +def _escaped(text: str) -> str: + """A path, a query or a fragment in its one form: what a URI carries as it is stays, and + the rest is percent-encoded.""" + return _REWRITTEN.sub(_rewritten, text) + + +def _path(text: str) -> str: + """A path in its one form, without its . and .. segments (RFC 3986, 5.2.4): a .. takes the + segment before it and never the root, and a path that ends in one ends in a slash.""" + kept: list[str] = [] + segments = _escaped(text or "/").split("/")[1:] + for index, segment in enumerate(segments): + if segment == ".." and kept: + kept.pop() + if segment not in (".", ".."): + kept.append(segment) + elif index == len(segments) - 1: + kept.append("") + return "/" + "/".join(kept) + + +def _ipv6_text(address: ipaddress.IPv6Address) -> str: + """An IPv6 address in its one short form: its groups in lower-case hexadecimal without + leading zeros, and the first of its longest runs of two or more zero groups as a double + colon. Written out here, never asked of the ipaddress module, whose own text of a mapped + address differs from one Python version to the next.""" + groups = [f"{int.from_bytes(address.packed[at : at + 2], 'big'):x}" for at in range(0, 16, 2)] + start, length, run = 0, 0, 0 + for index, group in enumerate(groups): + run = run + 1 if group == "0" else 0 + if run > length: + start, length = index - run + 1, run + if length < 2: + return ":".join(groups) + return f"{':'.join(groups[:start])}::{':'.join(groups[start + length :])}" + + +def _url_port(text: str, default: int) -> int: + """The port a URL names - ASCII digits, from 1 to 65535 - or the scheme's own for none.""" + if not text: + return default + port = _whole(text) if _DIGITS.fullmatch(text) else None + if port is None or not 1 <= port <= 65535: + raise AppException(400, _INVALID_PORT) + return port + + +def _bracketed_address(inside: str) -> str: + """What the brackets of a URL hold, as the short form of the IPv6 address it is; a zone, an + IPv4 address and anything else is no address the tools read.""" + if "%" in inside: + raise AppException(400, _NOT_A_WEB_ADDRESS) + try: + return _ipv6_text(ipaddress.IPv6Address(inside)) + except ValueError as exc: + raise AppException(400, _NOT_A_WEB_ADDRESS) from exc + + +def _url_host(name: str) -> str: + """The host a URL names outside brackets, in lower case: a name, or an IPv4 address in + dotted decimal - which a host is as soon as its last label spells a number - without the + dots at its end.""" + host = name.lower() + bare = host.rstrip(".") + if not bare: + raise AppException(400, "url has no host") + if not _HOST_NAME.fullmatch(name): + raise AppException(400, _INVALID_HOST) + if not _NUMBER_LABEL.search(bare): + return host + if not _DOTTED_DECIMAL.fullmatch(bare) or any(int(part) > 255 for part in bare.split(".")): + raise AppException(400, f"{name} {_NOT_DOTTED_DECIMAL}") + return bare + + +def _url_host_and_port(authority: str, default: int) -> tuple[str, int]: + """The host and the port of a URL's authority: an address in brackets and what follows + them, or a name up to its first colon.""" + if not authority.startswith("["): + name, _, port = authority.partition(":") + return _url_host(name), _url_port(port, default) + inside, closed, rest = authority[1:].partition("]") + if not closed or (rest and not rest.startswith(":")): + raise AppException(400, _NOT_A_WEB_ADDRESS) + return _bracketed_address(inside), _url_port(rest[1:], default) + + +def _split_reference(text: str) -> tuple[str, str | None, str]: + """A URL or a reference as its part before the query, its query - None for none - and its + fragment.""" + text, _, fragment = text.partition("#") + head, mark, query = text.partition("?") + return head, query if mark else None, fragment + + +@dataclass(frozen=True) +class WebAddress: + """A web address taken apart, each part in its one form: the scheme, the host - an IPv6 + address without its brackets - the port it means, the path, the query and the fragment, + empty for none.""" + + scheme: str + host: str + port: int + path: str + query: str + fragment: str = "" + + @property + def authority(self) -> str: + """The host, in brackets when it is an IPv6 address, and the port when it is not the + scheme's own.""" + host = f"[{self.host}]" if ":" in self.host else self.host + return host if self.port == _DEFAULT_PORTS[self.scheme] else f"{host}:{self.port}" + + @property + def target(self) -> str: + """The path and the query, as a request names them.""" + return f"{self.path}?{self.query}" if self.query else self.path + + @property + def url(self) -> str: + """The address in its one form, without its fragment.""" + return f"{self.scheme}://{self.authority}{self.target}" + + @property + def href(self) -> str: + """The address with its fragment, as a link names it.""" + return f"{self.url}#{self.fragment}" if self.fragment else self.url + + +def _held(address: WebAddress) -> WebAddress: + """An address the tools take: one longer than MAX_URL_LENGTH in its one form is a 400, so + what is asked of a robots.txt and of a server has a bound.""" + if len(address.href) > MAX_URL_LENGTH: + raise AppException(400, _TOO_LONG) + return address + + +def read_url(text: str) -> WebAddress: + """A URL taken apart by the rules above; one they do not take is a 400 that names the + rule.""" + head, query, fragment = _split_reference(_stripped(text)) + scheme = _SCHEME.match(head) + name = scheme.group(1).lower() if scheme else "" + if scheme is None or name not in _DEFAULT_PORTS or not head.startswith("//", scheme.end()): + raise AppException(400, _NOT_A_WEB_ADDRESS) + authority, slash, path = head[scheme.end() + 2 :].partition("/") + if "@" in authority: + raise AppException(400, "url must not carry credentials") + host, port = _url_host_and_port(authority, _DEFAULT_PORTS[name]) + return _held( + WebAddress(name, host, port, _path(slash + path), _escaped(query or ""), _escaped(fragment)) + ) + + +def _resolved(base: WebAddress, text: str) -> WebAddress: + """A reference as the address it names when it is read at a base address (RFC 3986, 5.2): + an address of its own, one that starts at the base's scheme, at its host or at its path, or + the base itself with another query or fragment. A reference that names the base's own + scheme and no host is read as what follows the scheme, the loose reading of 5.2.2.""" + head, query, fragment = _split_reference(text) + scheme = _SCHEME.match(head) + if scheme and (scheme.group(1).lower() != base.scheme or head.startswith("//", scheme.end())): + return read_url(text) + if scheme: + head = head[scheme.end() :] + if head.startswith("//"): + return read_url(f"{base.scheme}:{text}") + if not head: + path = base.path + query = base.query if query is None else query + elif head.startswith("/"): + path = head + else: + path = base.path[: base.path.rfind("/") + 1] + head + return _held( + WebAddress( + base.scheme, + base.host, + base.port, + _path(path), + _escaped(query or ""), + _escaped(fragment), + ) + ) + + +def resolve_url(base: str, reference: str) -> str: + """A reference found at an address - a link of a page, the Location of a redirect - as the + address it names, in its one form and with its fragment. A reference that names no web + address stays as it is written, without what a browser strips from it.""" + text = _stripped(reference) + try: + return _resolved(read_url(base), text).href + except AppException: + return text + + # --- HTML to text, in-house ---------------------------------------------------------------------- _DROP_TAGS = frozenset( @@ -1542,15 +2008,6 @@ def _docx_text(data: bytes, relative: str) -> str: _SPACES = re.compile(r"[ \t\r\n\f\v]+") -def _safe_join(base: str, href: str) -> str: - """A reference joined to the address it was read at; one that cannot be read as an address - stays as written.""" - try: - return urljoin(base, href) - except ValueError: - return href - - def _is_chrome(attrs: list[tuple[str, str | None]]) -> bool: for name, value in attrs: if name == "role" and (value or "").strip().lower() in _DROP_ROLES: @@ -1621,11 +2078,12 @@ def _end_link(self) -> None: def _start_link(self, attrs: list[tuple[str, str | None]]) -> None: """Open a link when the element has a target a reader can follow - not a fragment, a - script, a mail or a phone link; the link that was open is closed first.""" - href = dict(attrs).get("href") - if href and not href.lower().startswith(("#", "javascript:", "mailto:", "tel:")): + script, a mail or a phone link, told once what a browser strips from a target is gone; + the link that was open is closed first.""" + target = _stripped(dict(attrs).get("href") or "") + if target and not target.lower().startswith(("#", "javascript:", "mailto:", "tel:")): self._end_link() - self._href = _safe_join(self.base_url, href) if self.base_url else href + self._href = resolve_url(self.base_url, target) if self.base_url else target self._link_text = [] # -- the parser's callbacks @@ -1787,7 +2245,7 @@ def parse_host_rules(entries: tuple[str, ...]) -> tuple[HostRule, ...]: a host pattern with an optional scheme and port; a path, a query or credentials are refused.""" rules: list[HostRule] = [] for entry in entries: - text = entry.strip() + text = entry.strip(_BLANKS) scheme = "https" if "://" in text: scheme, _, text = text.partition("://") @@ -1808,12 +2266,16 @@ def _not_a_host_pattern(entry: str) -> ToolsError: ) -def _is_address(text: str) -> bool: +def _address_text(text: str) -> str | None: + """An address as a URL's host names it - an IPv6 address in its one short form - or None + for a text that is no address, or one with a zone, which no URL the tools read can name.""" + if "%" in text: + return None try: - ipaddress.ip_address(text) + address = ipaddress.ip_address(text) except ValueError: - return False - return True + return None + return _ipv6_text(address) if isinstance(address, ipaddress.IPv6Address) else text def _host_and_port(entry: str, text: str) -> tuple[str, int | None]: @@ -1825,39 +2287,27 @@ def _host_and_port(entry: str, text: str) -> tuple[str, int | None]: inside, closed, rest = text[1:].partition("]") if not closed: raise _not_a_host_pattern(entry) - if _is_address(inside): + address = _address_text(inside) + if address is not None: if rest and not rest.startswith(":"): raise _not_a_host_pattern(entry) - return inside, (_port(entry, rest[1:]) if rest else None) + return address, (_port(entry, rest[1:]) if rest else None) if text.count(":") == 1: host, _, port_text = text.partition(":") return host, _port(entry, port_text) - return text, None + return _address_text(text) or text, None def _port(entry: str, text: str) -> int: - try: - port = int(text) - except ValueError as exc: - raise ToolsError(f"{WEB_ALLOW}: {entry} - the port must be a number") from exc - if not 1 <= port <= 65535: + """The port an entry names: ASCII digits, from 1 to 65535.""" + if not _DIGITS.fullmatch(text): + raise ToolsError(f"{WEB_ALLOW}: {entry} - the port must be a number") + port = _whole(text) + if port is None or not 1 <= port <= 65535: raise ToolsError(f"{WEB_ALLOW}: {entry} - the port must be between 1 and 65535") return port -# what a URL is told when it is no http(s) address, or none the reader can take apart -_NOT_A_WEB_ADDRESS = "url must start with https:// (or http:// for a host listed with it)" - - -def _url_parts(url: str) -> SplitResult: - """A URL taken apart; one the reader refuses - brackets that hold no address - is no web - address.""" - try: - return urlsplit(url.strip()) - except ValueError as exc: - raise AppException(400, _NOT_A_WEB_ADDRESS) from exc - - @dataclass(frozen=True) class WebSandbox: """The allowlist and the limits of the web tools.""" @@ -1887,20 +2337,10 @@ def matches(self, host: str, scheme: str, port: int) -> tuple[bool, bool]: def check_url(self, url: str) -> SplitResult: """The URL a tool may fetch, by the allowlist alone (no network): an http(s) URL without credentials, whose host is listed for its scheme and port. Anything else is a 400 that - names the rule; the fragment is dropped.""" - parts = _url_parts(url) - scheme = parts.scheme.lower() - if scheme not in ("http", "https"): - raise AppException(400, _NOT_A_WEB_ADDRESS) - if parts.username is not None or parts.password is not None: - raise AppException(400, "url must not carry credentials") - host = (parts.hostname or "").lower().rstrip(".") - if not host: - raise AppException(400, "url has no host") - try: - port = parts.port or (443 if scheme == "https" else 80) - except ValueError as exc: - raise AppException(400, "url has an invalid port") from exc + names the rule. The URL comes back in its one form, the fragment dropped.""" + address = read_url(url.strip(_BLANKS)) + scheme, port = address.scheme, address.port + host = address.host.rstrip(".") listed, allowed = self.matches(host, scheme, port) if not allowed: if listed and scheme == "http": @@ -1913,8 +2353,7 @@ def check_url(self, url: str) -> SplitResult: raise AppException( 400, f"{host} is not one of the sites this agent may reach ({WEB_ALLOW})" ) - netloc = parts.netloc.rsplit("@", 1)[-1] - return SplitResult(scheme, netloc, parts.path or "/", parts.query, "") + return SplitResult(scheme, address.authority, address.path, address.query, "") async def pin(self, host: str, port: int) -> str: """The address a host resolves to, checked against the private ranges, so the request is @@ -2036,9 +2475,13 @@ def load_web_sandbox() -> WebSandbox | None: rules=parse_host_rules(entries), allow_private=_bool_setting(WEB_ALLOW_PRIVATE, False), max_bytes=_int_setting(WEB_MAX_BYTES, DEFAULT_WEB_MAX_BYTES, floor=1024), - timeout_ms=_int_setting(WEB_TIMEOUT_MS, DEFAULT_WEB_TIMEOUT_MS, floor=MIN_WEB_TIMEOUT_MS), + timeout_ms=_int_setting( + WEB_TIMEOUT_MS, DEFAULT_WEB_TIMEOUT_MS, floor=MIN_WEB_TIMEOUT_MS, most=MAX_TIMER_MS + ), crawl_max_pages=_int_setting(WEB_CRAWL_MAX_PAGES, CRAWL_PAGES_CAP, cap=CRAWL_PAGES_CAP), - crawl_delay_ms=_int_setting(WEB_CRAWL_DELAY_MS, DEFAULT_CRAWL_DELAY_MS, floor=0), + crawl_delay_ms=_int_setting( + WEB_CRAWL_DELAY_MS, DEFAULT_CRAWL_DELAY_MS, floor=0, most=MAX_TIMER_MS + ), page_max_chars=_int_setting(WEB_PAGE_MAX_CHARS, DEFAULT_PAGE_MAX_CHARS, floor=100), ) @@ -2080,9 +2523,14 @@ def is_text(self) -> bool: _META_CHARSET = re.compile(rb"""]+charset=["']?\s*([a-z0-9_.:-]+)""", re.IGNORECASE) +# the encodings whose byte-order mark at the start of a body is no part of its text +_MARKED_ENCODINGS = ("utf-8", "utf-16-le", "utf-16-be") + + def decode_body(fetched: Fetched) -> str: """The body as text: the charset of the content type, else the one a ``meta`` tag names, else - UTF-8; undecodable bytes are replaced, never an error.""" + UTF-8, without a byte-order mark at its start; undecodable bytes are replaced, never an + error.""" charset = fetched.charset if charset is None and fetched.is_html: match = _META_CHARSET.search(fetched.data[:4096]) @@ -2092,10 +2540,11 @@ def decode_body(fetched: Fetched) -> str: if not name: continue try: - return fetched.data.decode(name, errors="replace") + text = fetched.data.decode(name, errors="replace") except LookupError: continue - return fetched.data.decode("utf-8", errors="replace") + return _without_mark(text) if codecs.lookup(name).name in _MARKED_ENCODINGS else text + return _without_mark(fetched.data.decode("utf-8", errors="replace")) def _host_header(parts: SplitResult) -> str: @@ -2106,6 +2555,98 @@ def _host_header(parts: SplitResult) -> str: return host if parts.port in (None, default) else f"{host}:{parts.port}" +# --- robots.txt, read by RFC 9309 - the same reader in both packs -------------------------------- + +# a line of robots.txt ends at a carriage return, a line feed, or the two together +_ROBOTS_LINE_END = re.compile(r"\r\n?|\n") +# the product token a user-agent line names: the letters, hyphens and underscores it starts with +_PRODUCT_TOKEN = re.compile(r"[A-Za-z_-]*") + + +def _robots_groups(text: str) -> list[tuple[list[str], list[tuple[bool, str]]]]: + """The groups of a robots.txt, each as the agents it names and its rules - whether a rule + allows, and its path pattern. A group starts at a user-agent line, takes the user-agent + lines that follow it, and then the Allow and Disallow lines up to the next user-agent line; + a comment runs from a # to the end of its line, and any other line counts for nothing.""" + groups: list[tuple[list[str], list[tuple[bool, str]]]] = [] + for line in _ROBOTS_LINE_END.split(text): + name, colon, rest = line.partition("#")[0].partition(":") + field, value = name.strip(" \t").lower(), rest.strip(" \t") + if not colon: + continue + if field == "user-agent": + if not groups or groups[-1][1]: + groups.append(([], [])) + token = _PRODUCT_TOKEN.match(value) + groups[-1][0].append("*" if value == "*" or token is None else token.group().lower()) + elif field in ("allow", "disallow") and groups: + groups[-1][1].append((field == "allow", value)) + return groups + + +def _in_order(parts: tuple[str, ...], subject: str) -> bool: + """Whether a subject is the parts of a pattern in their order, with any run of characters + where a star stood between two of them: the first part starts the subject, the last one + ends it, and each part between them is looked for once, from where the part before it + ended. So the time is bounded by the subject's length plus the pattern's, never by their + product - a robots.txt is another site's text, and it is asked about every page.""" + first, last = parts[0], parts[-1] + if len(parts) == 1: + return subject == first + at, end = len(first), len(subject) - len(last) + if end < at or not subject.startswith(first) or not subject.endswith(last): + return False + for part in parts[1:-1]: + at = subject.find(part, at, end) + if at < 0: + return False + at += len(part) + return True + + +@dataclass(frozen=True) +class Robots: + """The rules of a robots.txt that the tools obey, each as whether it allows, how long its + pattern is and the parts the pattern is matched as: what stands between its stars, with a + star added at its end unless a $ ends it there.""" + + rules: tuple[tuple[bool, int, tuple[str, ...]], ...] = () + + def can_fetch(self, path: str) -> bool: + """Whether a path - with its query, as an address names the two - may be fetched: the + rule with the longest pattern that matches decides, an Allow before a Disallow of the + same length; a path no rule matches is allowed, and so is /robots.txt itself.""" + subject = _escaped(path) + best = (0, True) + if subject == "/robots.txt": + return True + for allow, length, parts in self.rules: + if (length, allow) > best and _in_order(parts, subject): + best = (length, allow) + return best[1] + + +def parse_robots(text: str) -> Robots: + """The rules of a robots.txt for the tools, by RFC 9309: the rules of every group that names + the tools' product token, in any letter case - or, when no group names it, of every group + for ``*``. A rule without a pattern says nothing. A pattern is compared in the form the + tools give a path, and matched part by part between its stars, so a rule takes a time + bounded by its length plus the path's, however many stars it has.""" + groups = _robots_groups(text) + token = ROBOTS_AGENT.lower() + agent = token if any(token in agents for agents, _rules in groups) else "*" + rules: list[tuple[bool, int, tuple[str, ...]]] = [] + for agents, group_rules in groups: + if agent not in agents: + continue + for allow, written in group_rules: + pattern = _escaped(written) + if pattern: + matched = pattern[:-1] if pattern.endswith("$") else f"{pattern}*" + rules.append((allow, len(pattern), tuple(matched.split("*")))) + return Robots(tuple(rules)) + + def _under(path: str, include: str) -> bool: """Whether a link's path is inside the crawl's include: a prefix when the include starts with a slash, else anywhere in the path - a model names a section as `guides/` as often as `/guides/`.""" @@ -2118,7 +2659,7 @@ class _Crawl: links, the links waiting and the ones seen, the pages read, what is left of the text budget, how many pages were fetched and whether the result was cut.""" - site: tuple[str, str, int | None] + site: tuple[str, str, int] include: str | None max_depth: int queue: deque[tuple[str, int]] @@ -2129,38 +2670,28 @@ class _Crawl: truncated: bool = False -def _site(parts: SplitResult) -> tuple[str, str, int | None]: - """The site a URL is on, as a crawl compares it: its scheme, its host as the URL names it - and its port.""" - return parts.scheme.lower(), (parts.hostname or "").lower(), parts.port +def _site(address: WebAddress) -> tuple[str, str, int]: + """The site an address is on, as a crawl compares it: its scheme, its host and the port it + means - the scheme's own when it names none.""" + return address.scheme, address.host, address.port def _follow_links(links: list[str], depth: int, crawl: _Crawl) -> None: """The links of a page that a crawl goes on to, one link deeper: the ones on its own site and - inside its include, each once and without its fragment. A link that cannot be read as an - address - brackets that hold none, a port that is no number - is passed over.""" + inside its include, each once, in its one form and without its fragment. A link that is no + web address the tools read is passed over.""" for link in links: try: - candidate = urlsplit(link) - site = _site(candidate) - except ValueError: + address = read_url(link) + except AppException: continue - if site != crawl.site: + if _site(address) != crawl.site: continue - if crawl.include and not _under(candidate.path, crawl.include): + if crawl.include and not _under(address.path, crawl.include): continue - normalized = urlunsplit( - ( - candidate.scheme.lower(), - candidate.netloc, - candidate.path or "/", - candidate.query, - "", - ) - ) - if normalized not in crawl.seen: - crawl.seen.add(normalized) - crawl.queue.append((normalized, depth + 1)) + if address.url not in crawl.seen: + crawl.seen.add(address.url) + crawl.queue.append((address.url, depth + 1)) class WebTools: @@ -2202,13 +2733,15 @@ async def _body(self, response: aiohttp.ClientResponse) -> tuple[bytearray, bool async def _request(self, session: aiohttp.ClientSession, current: str) -> Fetched | str: """One request of a fetch, through the allowlist and the address check: the response, or - the URL a redirect names - which the next request checks like the first.""" + the URL a redirect names - which the next request checks like the first. The request + names the path and the query as they were checked, never rewritten by the client.""" parts = self.sandbox.check_url(current) host = (parts.hostname or "").lower().rstrip(".") port = parts.port or (443 if parts.scheme == "https" else 80) address = await self.sandbox.pin(host, port) pinned_host = f"[{address}]" if ":" in address else address - pinned = urlunsplit((parts.scheme, f"{pinned_host}:{port}", parts.path, parts.query, "")) + target = f"{parts.path}?{parts.query}" if parts.query else parts.path + pinned = URL(f"{parts.scheme}://{pinned_host}:{port}{target}", encoded=True) extra: dict[str, Any] = {"server_hostname": host} if parts.scheme == "https" else {} try: async with session.get( @@ -2216,7 +2749,7 @@ async def _request(self, session: aiohttp.ClientSession, current: str) -> Fetche ) as response: location = response.headers.get("Location") if response.status in REDIRECT_STATUSES and location: - return _safe_join(urlunsplit(parts), location) + return resolve_url(urlunsplit(parts), location) data, truncated = await self._body(response) content_type = (response.content_type or "").lower() return Fetched( @@ -2284,19 +2817,18 @@ async def web_fetch(self, _headers: dict[str, str], body: Body) -> Any: "truncated": fetched.truncated or cut, } - async def _robots(self, parts: SplitResult) -> urllib.robotparser.RobotFileParser | None: - """The site's robots.txt, read through the same checks; a site without one allows all.""" - robots_url = urlunsplit((parts.scheme, parts.netloc, "/robots.txt", "", "")) + async def _robots(self, start: WebAddress) -> Robots | None: + """The site's robots.txt, read through the same checks; a site without one, or with one + that cannot be read, allows all.""" + robots_url = f"{start.scheme}://{start.authority}/robots.txt" try: fetched = await self.fetch(robots_url) except AppException as exc: - log.info("web.crawl robots.txt of %s not read (%d)", parts.hostname, exc.status) + log.info("web.crawl robots.txt of %s not read (%d)", start.host, exc.status) return None if fetched.status != 200 or not (fetched.is_text or fetched.is_html): return None - parser = urllib.robotparser.RobotFileParser() - parser.parse(decode_body(fetched).splitlines()) - return parser + return parse_robots(decode_body(fetched)) async def _visit_page(self, crawl: _Crawl, current: str, depth: int) -> bool: """One page of a crawl, fetched after the crawl's delay: its text joins the pages, inside @@ -2350,22 +2882,22 @@ async def web_crawl(self, _headers: dict[str, str], body: Body) -> Any: include = args.get("include") if include is not None and not isinstance(include, str): raise AppException(400, "include must be a string") - start = self.sandbox.check_url(url) + start = read_url(urlunsplit(self.sandbox.check_url(url))) site = _site(start) robots = await self._robots(start) - start_url = urlunsplit(start) crawl = _Crawl( site=site, - include=include, + # compared with a link's path, so in the form a path is given + include=None if include is None else _escaped(include), max_depth=max_depth, - queue=deque([(start_url, 0)]), - seen={start_url}, + queue=deque([(start.url, 0)]), + seen={start.url}, pages=[], budget=CRAWL_RESULT_MAX_CHARS, ) while crawl.queue and len(crawl.pages) < max_pages: current, depth = crawl.queue.popleft() - if robots is not None and not robots.can_fetch(ROBOTS_AGENT, current): + if robots is not None and not robots.can_fetch(read_url(current).target): continue if await self._visit_page(crawl, current, depth): break @@ -2431,7 +2963,7 @@ def load_graph_sandbox() -> GraphSandbox | None: delete=_bool_setting(GRAPH_DELETE, False), max_rows=_int_setting(GRAPH_MAX_ROWS, ROWS_DEFAULT, cap=ROWS_CAP), timeout_ms=_int_setting( - GRAPH_TIMEOUT_MS, DEFAULT_GRAPH_TIMEOUT_MS, floor=MIN_WEB_TIMEOUT_MS + GRAPH_TIMEOUT_MS, DEFAULT_GRAPH_TIMEOUT_MS, floor=MIN_WEB_TIMEOUT_MS, most=MAX_TIMER_MS ), ingest_max_nodes=_int_setting(GRAPH_INGEST_MAX_NODES, DEFAULT_INGEST_MAX_NODES), ) diff --git a/extensions/agent-tools/resources/application.yml b/extensions/agent-tools/resources/application.yml index 259cd79..17fa270 100644 --- a/extensions/agent-tools/resources/application.yml +++ b/extensions/agent-tools/resources/application.yml @@ -37,6 +37,9 @@ tools.file.hidden: false tools.file.write.extensions: '' # a line file.search returns is cut to this many characters tools.file.line.max.chars: 500 +# how long a file.search by regular expression may take, in milliseconds (100 at least): the search +# is ended there and answers a 408 +tools.file.search.timeout.ms: 10000 # the most characters file.extract returns of a document (PDF and Word need the documents extra: # pip install 'mercury-composable[documents]'; without it file.extract does not register) tools.file.extract.max.chars: 60000 diff --git a/tests/test_agent_tools.py b/tests/test_agent_tools.py index 04bf0fd..d993c46 100644 --- a/tests/test_agent_tools.py +++ b/tests/test_agent_tools.py @@ -20,6 +20,7 @@ import logging import os import re +import subprocess import sys import time from collections.abc import AsyncIterator, Callable, Iterator @@ -130,6 +131,28 @@ def _probes(block: str) -> list[list[str]]: return [line.split() for line in block.splitlines() if line and not line.startswith("#")] +def _answers(block: str) -> list[tuple[str, str]]: + """The rows of a block that says `probe => answer`: every line that is not a comment.""" + lines = [line for line in block.split("\n") if line and not line.startswith("#")] + return [(probe, answer) for probe, _, answer in (line.partition(" => ") for line in lines)] + + +def _decoded(text: str) -> str: + """A probe's text with every \\uXXXX in it as the character it names.""" + return re.sub(r"\\u([0-9a-f]{4})", lambda found: chr(int(found.group(1), 16)), text) + + +def _told(call: Callable[[], Any]) -> str: + """What a call answers, as the probes write it: the answer as JSON, the status and the + message of a refusal, or the message the boot stops with.""" + try: + return json.dumps(call()) + except AppException as exc: + return f"{exc.status} {exc.message}" + except tools.ToolsError as stop: + return str(stop) + + # --- the workspace ------------------------------------------------------------------------------- @@ -242,6 +265,111 @@ def test_arguments_are_checked_against_the_row(files: Any, body: Any, message: s assert message in text, text +# The probes of the number rule and of the switch rule. The Node.js twin's test file carries the +# same two texts, line for line: a value is a number, or a switch, to both packs or to neither. +NUMBER_PROBES = r""" +# a value as JSON, what an argument that is a whole number makes of it - max_bytes of file_read, on a file of 20 +# characters: how many it read, or the refusal - and what a setting makes of it - tools.file.max.bytes: the +# number it is, or why the boot stops +5 => 5 | 5 +5.0 => 5 | 5 +1 => 1 | 1 +9007199254740991 => 20 | 9007199254740991 +null => 20 | 262144 +5.5 => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +0 => 400 max_bytes must be at least 1 | tools.file.max.bytes must be at least 1 +-1 => 400 max_bytes must be at least 1 | tools.file.max.bytes must be at least 1 +9007199254740992 => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +1e20 => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +1e400 => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +-1e400 => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +true => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +false => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +[5] => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +{} => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +# a text of digits is a number to a setting, with white space around it at most, and never to an argument +"5" => 400 max_bytes must be an integer | 5 +" 5 " => 400 max_bytes must be an integer | 5 +"\u00a05\u3000" => 400 max_bytes must be an integer | 5 +"00000000000000000000005" => 400 max_bytes must be an integer | 5 +"9007199254740991" => 400 max_bytes must be an integer | 9007199254740991 +"9007199254740992" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"" => 400 max_bytes must be an integer | 262144 +"5 0" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"\ufeff5" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"+5" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"-5" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"1_0" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"\u0665" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"\uff15" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"5.0" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"1e1" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"0x5" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"true" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +""" + +SWITCH_PROBES = r""" +# a value as JSON, what an argument that is a switch makes of it - regex of file_search: the switch it is, or +# the refusal - and what a setting makes of it - tools.file.hidden: the switch it is, or why the boot stops +true => true | true +false => false | false +null => false | false +"" => 400 regex must be true or false | false +"true" => 400 regex must be true or false | true +"TRUE" => 400 regex must be true or false | true +"False" => 400 regex must be true or false | false +" true " => 400 regex must be true or false | true +"yes" => 400 regex must be true or false | tools.file.hidden must be true or false +"no" => 400 regex must be true or false | tools.file.hidden must be true or false +"on" => 400 regex must be true or false | tools.file.hidden must be true or false +"off" => 400 regex must be true or false | tools.file.hidden must be true or false +"1" => 400 regex must be true or false | tools.file.hidden must be true or false +"0" => 400 regex must be true or false | tools.file.hidden must be true or false +"maybe" => 400 regex must be true or false | tools.file.hidden must be true or false +1 => 400 regex must be true or false | tools.file.hidden must be true or false +0 => 400 regex must be true or false | tools.file.hidden must be true or false +5 => 400 regex must be true or false | tools.file.hidden must be true or false +[] => 400 regex must be true or false | tools.file.hidden must be true or false +""" + + +def test_numbers_and_switches_are_read_by_one_rule_in_both_packs( + tmp_path: Path, configure: Callable[[dict[str, Any]], None] +) -> None: + (tmp_path / "twenty.txt").write_text("abcdefghijklmnopqrst", encoding="utf-8") + (tmp_path / "lines.txt").write_text("abc\na.c\n", encoding="utf-8") + files = tools.FileTools(tools.FileSandbox(root=tmp_path.resolve())) + + def setting(key: str, value: Any, field: str) -> str: + configure({tools.FILE_ROOT: str(tmp_path), key: value}) + answer = _told(lambda: getattr(tools.load_file_sandbox(), field)) + configure({key: None}) + return answer + + def read(value: Any) -> int: + return len(files.read({}, {"path": "twenty.txt", "max_bytes": value})["text"]) + + def is_expression(value: Any) -> bool: + # as an expression a.c is in both lines, as a literal in one + found = files.search({}, {"pattern": "a.c", "regex": value, "glob": "lines.txt"}) + return len(found["matches"]) == 2 + + wrong: list[tuple[str, str, str]] = [] + for written, expected in _answers(NUMBER_PROBES): + value = json.loads(written) + argument = _told(lambda value=value: read(value)) + got = f"{argument} | {setting(tools.FILE_MAX_BYTES, value, 'max_bytes')}" + if got != expected: + wrong.append((written, expected, got)) + for written, expected in _answers(SWITCH_PROBES): + value = json.loads(written) + argument = _told(lambda value=value: is_expression(value)) + got = f"{argument} | {setting(tools.FILE_HIDDEN, value, 'hidden')}" + if got != expected: + wrong.append((written, expected, got)) + assert wrong == [], "an argument is what its row says; a setting is a number or a switch" + + def test_write_create_overwrite_and_append(files: Any, workspace: Path) -> None: created = files.write({}, {"path": "out/reports/summary.md", "content": "# Summary\n"}) assert created == {"path": "out/reports/summary.md", "bytes": 10, "mode": "create"} @@ -667,6 +795,231 @@ def found(pattern: str) -> list[tuple[int, str]]: assert found("four") == [(1, first)], "the carriage return before a line feed ends the line" +@pytest.fixture +def children(monkeypatch: pytest.MonkeyPatch) -> list[Any]: + """The child processes started during a test, in the order they were started.""" + started: list[Any] = [] + popen = subprocess.Popen + + def recording(*args: Any, **kwargs: Any) -> Any: + child = popen(*args, **kwargs) + started.append(child) + return child + + monkeypatch.setattr(subprocess, "Popen", recording) + return started + + +@pytest.mark.asyncio +async def test_a_search_by_regular_expression_ends_at_its_bound( + workspace: Path, configure: Callable[[dict[str, Any]], None], children: list[Any] +) -> None: + (workspace / "long.txt").write_text("a" * 40 + "b\n", encoding="utf-8") + configure({tools.FILE_ROOT: str(workspace), "tools.file.search.timeout.ms": 400}) + files = tools.FileTools(tools.load_file_sandbox()) + ticks = 0 + + async def tick() -> None: + nonlocal ticks + while True: + await asyncio.sleep(0.01) + ticks += 1 + + ticking = asyncio.create_task(tick()) + await asyncio.sleep(0.05) + began, before = time.perf_counter(), ticks + # the host runs a handler in a thread of its pool, and so does the test + body = {"pattern": "(a+)+$", "regex": True, "glob": "long.txt"} + outcome = await _astatus(asyncio.to_thread(files.search, {}, body)) + took = time.perf_counter() - began + ticking.cancel() + refusal = ( + "the search did not finish within 400 ms (tools.file.search.timeout.ms) - a simpler " + "regular expression, or a narrower path or glob, finishes sooner" + ) + assert outcome == (408, refusal) + assert took < 3, "the search ends at its bound, whatever the expression" + assert ticks - before >= 10, "the host went on while the expression ran" + assert [child.returncode is not None for child in children] == [True], ( + "the child was ended and waited for: nothing is left running" + ) + + +def test_a_child_whose_host_does_not_end_it_ends_itself( + workspace: Path, + configure: Callable[[dict[str, Any]], None], + children: list[Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + class Never: + """A timer that never fires: nothing in the host ends the child at the bound.""" + + daemon = True + + def __init__(self, *_arguments: Any): + self.started = False + + def start(self) -> None: + self.started = True + + def cancel(self) -> None: + self.started = False + + monkeypatch.setattr(tools.threading, "Timer", Never) + (workspace / "long.txt").write_text("a" * 40 + "b\n", encoding="utf-8") + configure({tools.FILE_ROOT: str(workspace), "tools.file.search.timeout.ms": 200}) + files = tools.FileTools(tools.load_file_sandbox()) + began = time.perf_counter() + body = {"pattern": "(a+)+$", "regex": True, "glob": "long.txt"} + assert _status(lambda: files.search({}, body)) == ( + 500, + "the search by regular expression ended before it answered", + ) + took = time.perf_counter() - began + assert 1 <= took < 4, "the child ended itself a second after the bound" + assert [child.returncode for child in children] == [1] + + +def test_a_search_by_regular_expression_runs_outside_the_host_and_leaves_nothing_running( + files: Any, children: list[Any] +) -> None: + found = files.search({}, {"pattern": r"def \w+\(", "regex": True}) + assert [(m["path"], m["line"]) for m in found["matches"]] == [ + ("src/app.py", 1), + ("src/app.py", 5), + ] + cased = files.search( + {}, {"pattern": "TODO|later", "regex": True, "case_sensitive": True, "context": 1} + ) + assert [(m["line"], m["before"], m["after"]) for m in cased["matches"]] == [ + (1, [], ["value = 1"]), + (3, ["value = 1"], ["TODO_COUNT = 2"]), + (4, ["# todo: later"], []), + ] + cut = files.search({}, {"pattern": "t.d.", "regex": True, "max_results": 2}) + assert (len(cut["matches"]), cut["truncated"]) == (2, True) + for body in ( + {"pattern": "(", "regex": True}, + {"pattern": "(", "regex": True, "path": "empty"}, + {"pattern": "(" * 30000 + "a" + ")" * 30000, "regex": True}, + ): + status, message = _status(lambda body=body: files.search({}, body)) + assert status == 400, "an expression that cannot be compiled is refused, files or none" + assert message.startswith("pattern is not a valid regular expression (") + assert files.search({}, {"pattern": "todo"})["files_searched"] == 5 + assert len(children) == 6, "a child for each search by regular expression, none for a literal" + assert [child.returncode is not None for child in children] == [True] * 6, ( + "each child was ended and waited for" + ) + + +def test_a_literal_is_searched_in_the_host_in_a_time_bounded_by_the_line( + files: Any, workspace: Path, children: list[Any] +) -> None: + (workspace / "wide.txt").write_text("a" * 300_000 + "\nNeedle In The Hay\n", encoding="utf-8") + # a line of one letter, a line that repeats its own start, and a line with a character of two units + repeated = "aab" * 31 + "aac" + said = ( + f"A Long Line of plain words, with one sign {chr(0x1F600)} in the middle of it, " + "goes on past 64 units" + ) + (workspace / "wider.txt").write_text(f"{'a' * 600_000}\n{repeated}\n{said}\n", encoding="utf-8") + # literals that nearly match at every place of a line + for pattern, glob in ( + ("a" * 40_000 + "b", "wide.txt"), + ("a" * 150_000 + "b" + "a" * 150_000, "wider.txt"), + ("ab" + "a" * 299_998, "wider.txt"), + ): + began = time.perf_counter() + assert files.search({}, {"pattern": pattern, "glob": glob})["matches"] == [] + assert time.perf_counter() - began < 5, ( + "a literal of any length costs the length of the line" + ) + found = files.search({}, {"pattern": "needle in the HAY", "glob": "wide.txt"}) + assert [(m["line"], m["text"]) for m in found["matches"]] == [(2, "Needle In The Hay")] + cased = {"pattern": "needle in the HAY", "glob": "wide.txt", "case_sensitive": True} + assert files.search({}, cased)["matches"] == [] + # literals of 64 units and of more: the same answers on either side of that length + for pattern, lines in ( + (repeated[3:], [2]), + (repeated[3:67], [2]), + (repeated[3:68], [2]), + (said[2:].upper(), [3]), + (said[2:] + "!", []), + ): + long = files.search({}, {"pattern": pattern, "glob": "wider.txt"}) + assert [m["line"] for m in long["matches"]] == lines, pattern + cased = {"pattern": said[2:].upper(), "glob": "wider.txt", "case_sensitive": True} + assert files.search({}, cased)["matches"] == [] + assert children == [], "a literal needs no child" + + +def test_a_byte_order_mark_is_no_part_of_a_text(files: Any, workspace: Path) -> None: + mark = b"\xef\xbb\xbf" + (workspace / "bom.txt").write_bytes(mark + b"# title\nbody\n") + (workspace / "bom.html").write_bytes(mark + b"

hello

") + (workspace / "two.txt").write_bytes(mark + mark + b"x\n") + assert files.read({}, {"path": "bom.txt"}) == { + "path": "bom.txt", + "bytes": 16, + "text": "# title\nbody\n", + "truncated": False, + } + assert files.read({}, {"path": "bom.txt", "max_bytes": 4})["text"] == "#" + assert files.read({}, {"path": "bom.txt", "max_bytes": 2})["text"] == "" + assert files.read({}, {"path": "two.txt"})["text"] == "\ufeffx\n", "the mark at the start, once" + first = files.search({}, {"pattern": "^#", "regex": True, "glob": "bom.txt"})["matches"] + assert [(m["line"], m["text"]) for m in first] == [(1, "# title")] + assert ( + files.search({}, {"pattern": "title", "glob": "bom.txt"})["matches"][0]["text"] == "# title" + ) + assert files.extract({}, {"path": "bom.txt"})["text"] == "--- page 1 ---\n# title\nbody" + assert files.extract({}, {"path": "bom.html"})["text"] == "--- page 1 ---\nhello" + for charset, data, text in ( + (None, mark + b"User-agent: *\n", "User-agent: *\n"), + ("utf-8", mark + b"hi", "hi"), + ("utf-16le", b"\xff\xfeh\x00i\x00", "hi"), + ("iso-8859-1", mark + b"hi", "\u00ef\u00bb\u00bfhi"), + ): + body = tools.Fetched("http://h/x", 200, "text/plain", charset, data, False) + assert tools.decode_body(body) == text, charset + + +def test_a_walk_looks_at_the_scan_limit_and_says_that_it_was_cut( + glob_files: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + read: list[str] = [] + scandir = os.scandir + + def counting(path: str) -> Any: + read.append(os.path.relpath(path, glob_files.root)) + return scandir(path) + + monkeypatch.setattr(tools.os, "scandir", counting) + monkeypatch.setattr(tools, "SCAN_LIMIT", 5) + cut = glob_files.list({}, {"glob": "**/nothing-is-named-so"}) + assert cut == {"entries": [], "truncated": True}, "the walk stopped, and the result says so" + assert read == ["."], "five entries of the root were looked at, and no folder beneath it" + listed = glob_files.list({}, {}) + assert listed["truncated"] is True + assert len(listed["entries"]) <= 5 + searched = glob_files.search({}, {"pattern": "leaf", "glob": "**/leaf.*"}) + assert searched["truncated"] is True + assert searched["files_searched"] <= 5 + # a folder of two entries: the walk is cut only when an entry is left + monkeypatch.setattr(tools, "SCAN_LIMIT", 2) + for body in ({"path": "src/pkg/deep"}, {"path": "src/pkg/deep", "glob": "*"}): + whole = glob_files.list({}, body) + assert ([e["path"] for e in whole["entries"]], whole["truncated"]) == ( + ["src/pkg/deep/leaf.py", "src/pkg/deep/leaf.txt"], + False, + ), body + monkeypatch.setattr(tools, "SCAN_LIMIT", 1) + for body in ({"path": "src/pkg/deep"}, {"path": "src/pkg/deep", "glob": "*"}): + part = glob_files.list({}, body) + assert (len(part["entries"]), part["truncated"]) == (1, True), body + + # --- HTML to text -------------------------------------------------------------------------------- PAGE = """ Page Title @@ -764,6 +1117,69 @@ def test_an_address_that_cannot_be_read_stays_as_written() -> None: assert links == ["http://[bad", "//[bad/x", "http://h:port/x", "https://h/ok"] +# The probes of a link. The Node.js twin's test file carries the same text, line for line. +LINK_PROBES = r""" +# a link as a page at http://h/dir/page?q=1 writes it - \uXXXX for a character that cannot stand in a line - and +# the address it names, a dash for a target that is no link to follow +# a reference is read at the page's address: from its scheme, its host, its folder or itself +/docs/a => http://h/docs/a +b => http://h/dir/b +./b => http://h/dir/b +../b => http://h/b +../../b => http://h/b +b/../c/./d/ => http://h/dir/c/d/ +?x=2 => http://h/dir/page?x=2 +b?x=2#top => http://h/dir/b?x=2#top +//other.example/x => http://other.example/x +//OTHER.example:80/x => http://other.example/x +https://h/x => https://h/x +HTTP://H:80/x/../y#frag => http://h/y#frag +http://h./x => http://h./x +http:x => http://h/dir/x +http:/x => http://h/x +https:x => https:x +# what a browser strips is gone before the scheme is read +\u0020/docs/a\u0020 => http://h/docs/a +\u0009/docs/a\u000a => http://h/docs/a +/do\u0009cs/\u000aa => http://h/docs/a +\u0020javascript:run() => - +\u0009JavaScript:run() => - +java\u000ascript:run() => - +\u0020mailto:x@example.com => - +\u0020Tel:+1 => - +\u0020#top => - +\u0020\u0009 => - +\u00a0/docs/a => http://h/dir/%C2%A0/docs/a +# a backslash is no slash: it is a character a URI does not carry as it is +\\other.example\x => http://h/dir/%5C%5Cother.example%5Cx +/a\b?c\d => http://h/a%5Cb?c%5Cd +# the form of the path and the query +/a b?c d => http://h/a%20b?c%20d +/café => http://h/caf%C3%A9 +/%41%2f => http://h/A%2F +# no web address: the target stays as it is written +ftp://h/x => ftp://h/x +x:y => x:y +data:text/plain,hi => data:text/plain,hi +http://[bad => http://[bad +http://h:port/x => http://h:port/x +http://0177.0.0.1/ => http://0177.0.0.1/ +//h:99999/x => //h:99999/x +""" + + +def test_a_link_is_read_as_a_browser_reads_it() -> None: + wrong: list[tuple[str, str, str, list[str]]] = [] + for written, expected in _answers(LINK_PROBES): + page = f'

x

' + _title, text, links = tools.html_to_text(page, "http://h/dir/page?q=1", markdown=True) + got = "-" if text == "x" else text[4:-1] + followed = [] if got == "-" else [got.split("#", 1)[0]] + if (got, links) != (expected, followed): + wrong.append((written, expected, got, links)) + assert wrong == [], "a link names one address in both packs, written in one form" + + # --- the web sandbox without a network ----------------------------------------------------------- @@ -845,6 +1261,51 @@ def test_an_allowlist_entry_that_starts_with_a_class_is_a_pattern() -> None: ) +# The probes of an allowlist entry. The Node.js twin's test file carries the same text. +ENTRY_PROBES = r""" +# an entry of tools.web.allow - \uXXXX for a character that cannot stand in a line - and the rule it is: its +# pattern, its scheme and its port, a dash for none; or why the boot stops +host:8443 => host https 8443 +host:080 => host https 80 +host:65535 => host https 65535 +http://host:8 => host http 8 +[::1]:8080 => ::1 https 8080 +# an address is written in its one form, as a URL's host is +[0:0:0:0:0:0:0:1]:8080 => ::1 https 8080 +[::FFFF:127.0.0.1] => ::ffff:7f00:1 https - +0:0:0:0:0:0:0:1 => ::1 https - +[127.0.0.1] => 127.0.0.1 https - +# a port is the digits 0 to 9, from 1 to 65535 +host:+8 => tools.web.allow: host:+8 - the port must be a number +host:-8 => tools.web.allow: host:-8 - the port must be a number +host: 8 => tools.web.allow: host: 8 - the port must be a number +host:1_0 => tools.web.allow: host:1_0 - the port must be a number +host:8.0 => tools.web.allow: host:8.0 - the port must be a number +host:0x50 => tools.web.allow: host:0x50 - the port must be a number +host:\u0668\u0660 => tools.web.allow: host:\u0668\u0660 - the port must be a number +host:\uff18\uff10 => tools.web.allow: host:\uff18\uff10 - the port must be a number +host:\u00b2 => tools.web.allow: host:\u00b2 - the port must be a number +host: => tools.web.allow: host: - the port must be a number +[::1]:+8 => tools.web.allow: [::1]:+8 - the port must be a number +host:0 => tools.web.allow: host:0 - the port must be between 1 and 65535 +host:65536 => tools.web.allow: host:65536 - the port must be between 1 and 65535 +host:99999999999999999999999999 => tools.web.allow: host:99999999999999999999999999 - the port must be between 1 and 65535 +""" + + +def test_an_allowlist_entry_names_its_port_in_the_digits_0_to_9() -> None: + wrong: list[tuple[str, str, str]] = [] + for written, expected in _answers(ENTRY_PROBES): + try: + rule = tools.parse_host_rules((_decoded(written),))[0] + got = f"{rule.pattern} {rule.scheme} {rule.port if rule.port is not None else '-'}" + except tools.ToolsError as stop: + got = str(stop) + if got != _decoded(expected): + wrong.append((written, expected, got)) + assert wrong == [], "a port is ASCII digits from 1 to 65535, an address is in its one form" + + def test_an_exclamation_mark_negates_a_class_only_when_it_is_first() -> None: glob = tools.compile_glob("[b-a!x]") assert [glob.test(name) for name in ("x", "!", "y")] == [True, True, False], ( @@ -886,7 +1347,7 @@ def sandbox() -> Any: ("url", "expect"), [ ("https://docs.example.com/a/b?x=1#frag", "https://docs.example.com/a/b?x=1"), - ("https://DOCS.example.com", "https://DOCS.example.com/"), + ("https://DOCS.example.com", "https://docs.example.com/"), ("https://sub.example.org/", "https://sub.example.org/"), ("https://a.b.example.org/", "https://a.b.example.org/"), ("http://127.0.0.1:8080/x", "http://127.0.0.1:8080/x"), @@ -1258,6 +1719,132 @@ async def test_a_literal_host_is_classified_by_the_address_it_names() -> None: assert wrong == [], "the spelling of a literal never changes the kind of its address" +# The probes of the tools' own reader of a URL. The Node.js twin's test file carries the same +# text, line for line. +URL_READ_PROBES = r""" +# a URL - \uXXXX for a character that cannot stand in a line - and the one form the tools read it in, or the +# refusal; every host is listed, over http too +# the scheme and the host in lower case, the scheme's own port left out, an empty path a slash +https://docs.example.com/a/b?x=1#frag => https://docs.example.com/a/b?x=1 +https://DOCS.example.com => https://docs.example.com/ +HtTpS://Docs.Example.Com:443/x => https://docs.example.com/x +http://docs.example.com:80/x => http://docs.example.com/x +https://docs.example.com:80/x => https://docs.example.com:80/x +https://docs.example.com:0443/x => https://docs.example.com/x +https://docs.example.com:/x => https://docs.example.com/x +https://docs.example.com:65535/x => https://docs.example.com:65535/x +https://docs.example.com?x=1 => https://docs.example.com/?x=1 +https://docs.example.com#frag => https://docs.example.com/ +https://docs.example.com/p? => https://docs.example.com/p +https://docs.example.com/p?x=1?y=2 => https://docs.example.com/p?x=1?y=2 +http://a_b.example/ => http://a_b.example/ +http://A.B./x => http://a.b./x +http://xn--bcher-kva.example/ => http://xn--bcher-kva.example/ +# what a browser strips: the controls and the space at the ends, every tab and line break inside; and the white +# space both packs take, around the argument +\u0020https://docs.example.com/x\u0020 => https://docs.example.com/x +\u0009https://docs.example.com/x\u000a => https://docs.example.com/x +\u0000https://docs.example.com/x\u001f => https://docs.example.com/x +ht\u0009tps://docs.exa\u000ample.com/x\u000d => https://docs.example.com/x +\u00a0https://docs.example.com/x\u3000 => https://docs.example.com/x +\ufeffhttps://docs.example.com/x => 400 url must start with https:// (or http:// for a host listed with it) +https://docs.example.com/x\u0085 => https://docs.example.com/x%C2%85 +# a backslash is no slash: it is a character a URI does not carry as it is +https:\\docs.example.com\x => 400 url must start with https:// (or http:// for a host listed with it) +https://docs.example.com\x/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +https://docs.example.com/a\b?c\d => https://docs.example.com/a%5Cb?c%5Cd +# no web address: another scheme, or no two slashes after it +ftp://docs.example.com/ => 400 url must start with https:// (or http:// for a host listed with it) +docs.example.com/page => 400 url must start with https:// (or http:// for a host listed with it) +//docs.example.com/x => 400 url must start with https:// (or http:// for a host listed with it) +https:/docs.example.com/x => 400 url must start with https:// (or http:// for a host listed with it) +https:docs.example.com => 400 url must start with https:// (or http:// for a host listed with it) +# credentials, a host, a port +https://user@docs.example.com/ => 400 url must not carry credentials +https://user:pw@docs.example.com/ => 400 url must not carry credentials +https://@docs.example.com/ => 400 url must not carry credentials +https://docs.example.com/@x?y=@ => https://docs.example.com/@x?y=@ +https:///path => 400 url has no host +https:// => 400 url has no host +https://:443/ => 400 url has no host +https://./ => 400 url has no host +https://docs.example.com:0/x => 400 url has an invalid port +https://docs.example.com:65536/x => 400 url has an invalid port +https://docs.example.com:x/ => 400 url has an invalid port +https://docs.example.com:+8/ => 400 url has an invalid port +https://docs.example.com:8_0/ => 400 url has an invalid port +https://docs.example.com:\u0668/ => 400 url has an invalid port +https://docs.example.com:8:9/ => 400 url has an invalid port +http://[::1]:x/ => 400 url has an invalid port +# a name is letters, digits, hyphens, dots and underscores +http://b\u00fccher.example/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +http://ex%61mple.com/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +http://exa mple.com/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +http://a!b.example/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +http://\u212a.example/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +http://\uff11\uff12\uff17.\uff10.\uff10.\uff11/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +# a host whose last label spells a number is an address, written in dotted decimal and no other way +http://1.2.3.4/ => http://1.2.3.4/ +http://1.2.3.4./ => http://1.2.3.4/ +http://0.0.0.0/ => http://0.0.0.0/ +http://255.255.255.255:8080/ => http://255.255.255.255:8080/ +http://0177.0.0.1/ => 400 0177.0.0.1 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://2130706433/ => 400 2130706433 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://0x7f.1/ => 400 0x7f.1 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://0X7F000001/ => 400 0X7F000001 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://127.1/ => 400 127.1 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://127.000.000.001/ => 400 127.000.000.001 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://1.2.3.256/ => 400 1.2.3.256 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://1.2.3.4.5/ => 400 1.2.3.4.5 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://foo.1/ => 400 foo.1 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://0x/ => 400 0x is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://1e3/ => http://1e3/ +http://1.2.3.4x/ => http://1.2.3.4x/ +# an IPv6 address stands in brackets, without a zone, and is written in its one short form +http://[::1]:8080/a => http://[::1]:8080/a +http://[0:0:0:0:0:0:0:1]/ => http://[::1]/ +http://[::FFFF:127.0.0.1]/ => http://[::ffff:7f00:1]/ +http://[2001:DB8:0:0:1:0:0:1]/ => http://[2001:db8::1:0:0:1]/ +http://[1:0:0:2:0:0:0:3]:80/ => http://[1:0:0:2::3]/ +http://[fe80::1%25eth0]/ => 400 url must start with https:// (or http:// for a host listed with it) +http://[fe80::1%eth0]/ => 400 url must start with https:// (or http:// for a host listed with it) +http://[127.0.0.1]/ => 400 url must start with https:// (or http:// for a host listed with it) +http://[::1]x/ => 400 url must start with https:// (or http:// for a host listed with it) +http://[bad/ => 400 url must start with https:// (or http:// for a host listed with it) +# the path and the query: what a URI does not carry as it is becomes its bytes percent-encoded, an escape keeps +# its digits in upper case or becomes the letter, digit, hyphen, dot, underscore or tilde it stands for, and the +# path loses its . and .. segments +https://docs.example.com/a b?c d => https://docs.example.com/a%20b?c%20d +https://docs.example.com/café?é => https://docs.example.com/caf%C3%A9?%C3%A9 +https://docs.example.com/😀 => https://docs.example.com/%F0%9F%98%80 +https://docs.example.com/{y}|z^\u0060" => https://docs.example.com/%3Cx%3E%7By%7D%7Cz%5E%60%22 +https://docs.example.com/a;b=c,d/(x)!$&'*+@:[] => https://docs.example.com/a;b=c,d/(x)!$&'*+@:[] +https://docs.example.com/%41%7e%2f%3a%c3%a9 => https://docs.example.com/A~%2F%3A%C3%A9 +https://docs.example.com/a%zzb%?% => https://docs.example.com/a%25zzb%25?%25 +https://docs.example.com/a/../b => https://docs.example.com/b +https://docs.example.com/a/./b/ => https://docs.example.com/a/b/ +https://docs.example.com/a/%2e%2E/b => https://docs.example.com/b +https://docs.example.com/a/b/.. => https://docs.example.com/a/ +https://docs.example.com/a/b/. => https://docs.example.com/a/b/ +https://docs.example.com/../../x => https://docs.example.com/x +https://docs.example.com/a//b/.../c => https://docs.example.com/a//b/.../c +https://docs.example.com/p?a/../b => https://docs.example.com/p?a/../b +""" + + +def test_a_url_is_read_by_one_rule_in_both_packs() -> None: + sandbox = tools.WebSandbox(rules=tools.parse_host_rules(("http://*",))) + wrong: list[tuple[str, str, str]] = [] + for written, expected in _answers(URL_READ_PROBES): + try: + got = sandbox.check_url(_decoded(written)).geturl() + except AppException as exc: + got = f"{exc.status} {exc.message}" + if got != expected: + wrong.append((written, expected, got)) + assert wrong == [], "a URL has one form, and what is no URL is refused by the same words" + + @pytest.mark.asyncio async def test_pin_refuses_private_addresses_unless_allowed() -> None: closed = tools.WebSandbox( @@ -1281,6 +1868,213 @@ async def test_pin_refuses_private_addresses_unless_allowed() -> None: assert "cannot be resolved" in message +# The probes of the robots.txt reader. The Node.js twin's test file carries the same text. +ROBOTS_PROBES = r""" +# robots.txt files - each line of one after a bar, \r for a carriage return and \t for a tab - and under +# each file the paths a crawl asks about, with the answer +# the longest pattern that matches decides, and an Allow wins a tie +| User-agent: * +| Disallow: /private/ +| Allow: /private/public +| Disallow: /tie +| Allow: /tie +/docs/a allowed +/private/secret refused +/private/public/page allowed +/private allowed +/tie/x allowed +/robots.txt allowed +# the groups that name the tools' token, in any letter case and with a version, are one group, and no other counts +| User-agent: mercurycomposable +| Disallow: /only-us +| +| User-agent: * +| Disallow: / +| +| User-agent: MERCURYCOMPOSABLE/1.0 +| Disallow: /also-us +/only-us/x refused +/also-us refused +/docs allowed +# a group named by a part of the token is another agent's; the groups for * are one group +| User-agent: mercury +| Disallow: / +| User-agent: e +| Disallow: / +| User-agent: * +| Disallow: /a +| User-agent: * +| Disallow: /b +/a refused +/b/x refused +/c allowed +# the tools' own group decides even when it says nothing +| User-agent: MercuryComposable +| Disallow: +| User-agent: * +| Disallow: / +/anything allowed +# a star is any run of characters, a $ at the end of a pattern is the end of the path, and any other $ is itself +| User-agent: * +| Disallow: /*.pdf$ +| Disallow: /a*b +| Disallow: /img/*/raw +| Allow: /img/*/raw/ok$ +| Disallow: /end$ +| Disallow: /dollar$x +/x.pdf refused +/x.pdf?download allowed +/dir/x.pdf refused +/aXXb/more refused +/ab refused +/a allowed +/img/1/raw/x refused +/img/1/2/raw refused +/img/1/raw/ok allowed +/img/1/raw/ok/more refused +/end refused +/end/ allowed +/ended allowed +/dollar$x/y refused +# a pattern is matched against the path and the query, both in the form the tools give an address +| User-agent: * +| Disallow: /p?x=1 +| Disallow: /*?print= +| Disallow: /caf%C3%A9 +| Disallow: /a%2fb +| Disallow: /%7Euser +| Disallow: /sp ace +/p?x=1 refused +/p?x=12 refused +/p?y=1 allowed +/doc?print=1 refused +/doc allowed +/café refused +/caf%c3%a9/x refused +/a%2Fb refused +/a/b allowed +/~user/x refused +/%7euser refused +/sp%20ace refused +# a comment runs from a # to the end of its line; a line ends at a carriage return too; a field is read in any +# letter case, with spaces and tabs around it; a line without a colon, another record and a rule before any +# user-agent line count for nothing +| # a comment +| Disallow: /before-any-agent +| USER-AGENT : * # everyone +| \tdisallow\t:\t/tab # and a comment +| Crawl-delay: 10 +| Sitemap: https://h/sitemap.xml +| Disallow /no-colon +| DISALLOW: /upper\rDisallow: /cr +| Allow: /upper/ok#fragment +/before-any-agent allowed +/tab/x refused +/no-colon allowed +/upper/x refused +/cr refused +/upper/ok allowed +# only an Allow or a Disallow line ends the run of user-agent lines that starts a group +| User-agent: other +| Crawl-delay: 5 +| User-agent: * +| Disallow: /shared +| User-agent: third +| Disallow: /third +/shared refused +/third allowed +# a file without a group allows, and so does an empty one +| Disallow: / +/anything allowed +| +/anything allowed +# a pattern is matched from the start of the path, whatever it starts with +| User-agent: * +| Disallow: *.gif$ +| Disallow: private +/x.gif refused +/private allowed +# a rule of many stars is matched item by item +| User-agent: * +| Disallow: /*a*a*a*a*b +/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa allowed +/aaaab refused +""" + + +def _robots_files(block: str) -> list[tuple[str, list[list[str]]]]: + """The files of a block of robots probes, each with the paths asked about and the answers.""" + files: list[tuple[list[str], list[list[str]]]] = [] + for line in block.split("\n"): + if not line or line.startswith("#"): + continue + if not line.startswith("|"): + files[-1][1].append(line.split(" ")) + continue + if not files or files[-1][1]: + files.append(([], [])) + files[-1][0].append(line[2:].replace("\\r", "\r").replace("\\t", "\t")) + return [("\n".join(lines) + "\n", asked) for lines, asked in files] + + +def test_robots_txt_is_read_by_rfc_9309_in_both_packs() -> None: + wrong: list[tuple[str, str, str, str]] = [] + for text, asked in _robots_files(ROBOTS_PROBES): + robots = tools.parse_robots(text) + for path, answer in asked: + got = "allowed" if robots.can_fetch(path) else "refused" + if got != answer: + wrong.append((text, path, answer, got)) + assert wrong == [], "the longest pattern that matches decides, in the tools' group or in *" + + +def test_a_robots_rule_of_many_stars_is_answered_in_bounded_time() -> None: + began = time.perf_counter() + for stars in (4, 5, 12): + robots = tools.parse_robots(f"User-agent: *\nDisallow: /{'*a' * stars}*b\n") + assert robots.can_fetch("/" + "a" * 200) is True + assert robots.can_fetch("/" + "a" * 5000) is True + assert robots.can_fetch("/" + "a" * 5000 + "b") is False + many = tools.parse_robots("User-agent: *\n" + "Disallow: /*a*a*a*a*b\n" * 2000) + assert many.can_fetch("/" + "a" * 200) is True + assert time.perf_counter() - began < 5, ( + "the time is bounded by the rule's length times the path's, however many stars" + ) + + +def test_a_robots_txt_of_long_rules_is_answered_in_a_time_bounded_by_its_length() -> None: + """A rule is matched part by part between its stars, so its time is its length plus the + path's. Matched item by item, half a megabyte of such rules took half a minute a question.""" + rule = "Disallow: /*" + "a" * 1000 + "b" + robots = tools.parse_robots("User-agent: *\n" + "\n".join([rule] * 490) + "\n") + tiny = tools.parse_robots("User-agent: *\n" + "Disallow: *z\n" * 40_000) + began = time.perf_counter() + assert robots.can_fetch("/" + "a" * 2000) is True + assert robots.can_fetch("/" + "a" * 2000 + "b") is False + assert tiny.can_fetch("/" + "a" * 8000) is True + assert time.perf_counter() - began < 2, ( + "the time is bounded by the file's length and the path's" + ) + + +def test_an_address_longer_than_the_bound_is_refused() -> None: + """An address has a longest length, counted in its one form: a page may write a link of any + length, and every link is asked of a robots.txt and of a server.""" + at_the_bound = "https://docs.example.com/" + "a" * (tools.MAX_URL_LENGTH - 25) + assert len(tools.read_url(at_the_bound).href) == tools.MAX_URL_LENGTH + longer = (at_the_bound + "a", at_the_bound + "?q", at_the_bound + "#f") + for text in longer: + with pytest.raises(AppException) as refused: + tools.read_url(text) + assert (refused.value.status, refused.value.message) == ( + 400, + "url is longer than 8192 characters", + ) + # a link that long names no address the tools take: it stays as it is written + link = "/" + "a" * tools.MAX_URL_LENGTH + assert tools.resolve_url("https://docs.example.com/", link) == link + + # --- the fixture site ---------------------------------------------------------------------------- SITE_PAGES = { @@ -1309,7 +2103,26 @@ async def test_pin_refuses_private_addresses_unless_allowed() -> None: 'three, C.

' ), ), + "/wild": ( + "Wild", + ( + '

one, two, ' + 'three, four.

' + ), + ), + "/wild/a.tmp": ("Tmp", "

A file to leave alone.

"), + "/wild/b": ("B", "

A page, printed or viewed.

"), + "/wild/c.tmp": ("C", "

A file with a query.

"), } +# the fixture site's robots.txt: what a test puts here is served until the test ends +SITE_ROBOTS = {"text": "User-agent: *\nDisallow: /private/\n"} +# one page under many spellings, as the fixture site links it from /same on its own port +SAME_PAGE = ( + '

one ' + 'two three ' + 'four five six ' + 'seven

' +) def _page(title: str, body: str) -> str: @@ -1328,7 +2141,15 @@ async def page(request: web.Request) -> web.Response: return web.Response(text=_page(title, body), content_type="text/html") async def robots(_request: web.Request) -> web.Response: - return web.Response(text="User-agent: *\nDisallow: /private/\n", content_type="text/plain") + return web.Response(text=SITE_ROBOTS["text"], content_type="text/plain") + + async def same(request: web.Request) -> web.Response: + body = SAME_PAGE.replace("PORT", str(request.url.port)) + return web.Response(text=_page("Same", body), content_type="text/html") + + async def echo(request: web.Request) -> web.Response: + # the path and the query exactly as the request named them + return web.Response(text=request.raw_path, content_type="text/plain") async def plain(_request: web.Request) -> web.Response: return web.Response(text="plain text body\n", content_type="text/plain") @@ -1377,6 +2198,8 @@ async def missing(_request: web.Request) -> web.Response: for path in SITE_PAGES: app.router.add_get(path, page) app.router.add_get("/robots.txt", robots) + app.router.add_get("/same", same) + app.router.add_get("/echo/{rest:.*}", echo) app.router.add_get("/plain.txt", plain) app.router.add_get("/data.json", data) app.router.add_get("/image.png", image) @@ -1718,6 +2541,63 @@ async def test_an_address_that_cannot_be_read_fails_no_fetch_and_no_crawl( assert reply["visited"] == 2 +@pytest.mark.asyncio +async def test_a_crawl_asks_robots_txt_about_the_path_and_the_query( + site: str, web_tools: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setitem( + SITE_ROBOTS, + "text", + "User-agent: *\nDisallow: /private/\nDisallow: /wild/*.tmp$\nDisallow: /*?print=\n\n" + "User-agent: mercury\nDisallow: /wild/\n", + ) + reply = await web_tools.web_crawl({}, {"url": f"{site}/wild"}) + assert [p["url"] for p in reply["pages"]] == [ + f"{site}/wild", + f"{site}/wild/b?view=1", + f"{site}/wild/c.tmp?x", + ], "a star, a $ and a query are obeyed, and a group for another agent is not the tools'" + assert reply["visited"] == 3 + + +@pytest.mark.asyncio +async def test_a_crawl_knows_a_site_and_a_page_by_one_form( + site: str, configure: Callable[[dict[str, Any]], None], monkeypatch: pytest.MonkeyPatch +) -> None: + import ipaddress + + async def fixture_address(_host: str, _port: int) -> list[Any]: + return [ipaddress.ip_address("127.0.0.1")] + + monkeypatch.setattr(tools, "_resolve", fixture_address) + configure({**SITE_SETTINGS, tools.WEB_ALLOW: "http://*"}) + client = tools.WebTools(tools.load_web_sandbox()) + port = site.rsplit(":", 1)[1] + try: + reply = await client.web_crawl({}, {"url": f"HTTP://Fixture.TEST:{port}/same"}) + finally: + await client.close() + assert [p["url"] for p in reply["pages"]] == [ + f"http://fixture.test:{port}/same", + f"http://fixture.test:{port}/docs/c", + ] + assert reply["visited"] == 2, "a page is fetched once, however its links spell it" + + +@pytest.mark.asyncio +async def test_a_request_names_the_path_and_the_query_as_they_were_checked( + site: str, web_tools: Any +) -> None: + for written, asked in ( + ("/echo/a%3Ab%2fc?q=%27x%27&r=%3d", "/echo/a%3Ab%2Fc?q=%27x%27&r=%3D"), + ("/echo/x/../y/%2e%2e/z a?b c#d", "/echo/z%20a?b%20c"), + ("/echo/(a);b=c,d~e!$'*+@:[]", "/echo/(a);b=c,d~e!$'*+@:[]"), + ("/echo/caf\u00e9/%7Euser?\u00e9", "/echo/caf%C3%A9/~user?%C3%A9"), + ): + reply = await web_tools.web_fetch({}, {"url": f"{site}{written}"}) + assert (reply["url"], reply["text"]) == (f"{site}{asked}", asked), written + + # --- the clock ----------------------------------------------------------------------------------- @@ -1795,6 +2675,55 @@ async def test_a_bad_sandbox_stops_the_boot_by_name( assert "tools.web.timeout.ms must be an integer" in caplog.text +@pytest.mark.asyncio +async def test_a_setting_that_is_no_number_and_no_switch_stops_the_boot_by_name( + workspace: Path, configure: Callable[[dict[str, Any]], None], caplog: pytest.LogCaptureFixture +) -> None: + root = {tools.FILE_ROOT: str(workspace)} + sites = {tools.WEB_ALLOW: "docs.example.com"} + graph = {tools.GRAPH_URI: "bolt://graph.example:7687"} + for settings, message in ( + ({tools.TIME_ENABLED: "yes"}, "tools.time must be true or false"), + ({**root, tools.FILE_HIDDEN: 1}, "tools.file.hidden must be true or false"), + ({**root, tools.FILE_MAX_BYTES: "1_0"}, "tools.file.max.bytes must be an integer"), + ( + {**root, "tools.file.search.timeout.ms": 99}, + "tools.file.search.timeout.ms must be at least 100", + ), + ( + {**root, "tools.file.search.timeout.ms": 2147483648}, + "tools.file.search.timeout.ms must be at most 2147483647", + ), + ( + {**sites, tools.WEB_ALLOW_PRIVATE: "on"}, + "tools.web.allow.private must be true or false", + ), + ( + {**sites, tools.WEB_TIMEOUT_MS: 2147483648}, + "tools.web.timeout.ms must be at most 2147483647", + ), + ( + {**sites, tools.WEB_CRAWL_DELAY_MS: "4294967296"}, + "tools.web.crawl.delay.ms must be at most 2147483647", + ), + ({**graph, tools.GRAPH_WRITE: "1"}, "tools.graph.write must be true or false"), + ( + {**graph, tools.GRAPH_TIMEOUT_MS: 2147483648}, + "tools.graph.timeout.ms must be at most 2147483647", + ), + ): + configure(settings) + booting = tools.AgentTools(FunctionRegistry()) + with caplog.at_level(logging.ERROR), pytest.raises(SystemExit): + await booting.boot() + assert f"Built-in tools cannot start - {message}\n" in caplog.text, message + configure(dict.fromkeys(settings)) + configure({**root, "tools.file.search.timeout.ms": " 250 "}) + assert tools.load_file_sandbox().search_timeout_ms == 250 + configure({"tools.file.search.timeout.ms": None}) + assert tools.load_file_sandbox().search_timeout_ms == 10000 + + @pytest.mark.asyncio async def test_a_full_configuration_registers_every_tool_and_serves_them_through_the_bus( workspace: Path, @@ -2186,6 +3115,27 @@ def test_plan_ingest_refuses_by_rule(args: dict[str, Any], message: str) -> None assert message in text, text +def test_a_property_named_proto_is_kept_like_any_other() -> None: + args = json.loads( + '{"nodes": [{"key": "k", "label": "L", "properties": {"__proto__": 1, "ok": 2}},' + ' {"key": "m", "label": "L", "properties": {"__proto__": ["a"], "constructor": "c"}}],' + ' "relationships": [{"from": "k", "to": "m", "type": "T", "properties": {"__proto__": true}}]}' + ) + plan = tools.plan_ingest(args, max_nodes=5) + assert [list(row["properties"].items()) for row in plan.nodes["L"]] == [ + [("__proto__", 1), ("ok", 2)], + [("__proto__", ["a"]), ("constructor", "c")], + ] + assert list(plan.relationships["T"][0]["properties"].items()) == [("__proto__", True)] + nested = json.loads( + '{"nodes": [{"key": "k", "label": "L", "properties": {"__proto__": {"a": 1}}}]}' + ) + assert _status(lambda: tools.plan_ingest(nested, max_nodes=5)) == ( + 400, + "nodes[0].properties.__proto__ must be a scalar or a list of scalars", + ) + + # --- the knowledge graph: the tools over a fake backend ---------------------------------------- @@ -2796,8 +3746,25 @@ def test_pages_are_numbers_in_the_digits_0_to_9() -> None: ), spec assert tools.page_range(" 2 ", 12) == [2] assert tools.page_range("00002, 1-3", 12) == [2, 1, 3] - assert tools.page_range("9" * 5000, 12) == [], "a page beyond the document selects nothing" - assert tools.page_range("2-" + "9" * 5000, 3) == [2, 3] + assert tools.page_range("\u00a02\u3000,\u20283", 12) == [2, 3], "white space both packs take" + assert tools.page_range("9007199254740991", 12) == [], ( + "a page beyond the document selects nothing" + ) + assert tools.page_range("2-9007199254740991", 3) == [2, 3] + for spec in ( + "9007199254740992", + "9007199254740993-9007199254740992", + "2-9007199254740992", + "9" * 5000, + "2-" + "9" * 5000, + "\u00852", + "\ufeff2", + "2\u001f", + ): + assert _status(lambda spec=spec: tools.page_range(spec, 12)) == ( + 400, + "pages must be page numbers and ranges such as 1-3,7", + ), spec[:20] # --- the boot with the graph and the documents -------------------------------------------------- From 6b4e8f1c39e694e613c27adaec21ba96edac4c52 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:01 -0800 Subject: [PATCH 3/5] fix(llm-helper): the settings are read when the helper starts, and a switch, a time in milliseconds and a page list by one rule A start-up step reads the settings a request falls back on and builds the transcript store when one is named, so a wrong one stops the application by name. A switch is true or false and any other value stops the start. A time in milliseconds is at most 2147483647, the audit's retention at most 1000000d, a port at most 65535. In a page list white space is ignored around a number and refused inside one. A path is blank by the same 24 characters in both packs. Co-Authored-By: Claude Fable 5.2 --- extensions/llm-helper/README.md | 80 ++- extensions/llm-helper/llm_helper.py | 268 ++++++--- tests/test_llm_attachments.py | 22 +- tests/test_llm_helper.py | 144 ++++- tests/vectors/llm-attachments-vectors.json | 81 +++ tests/vectors/llm-helper-vectors.json | 658 ++++++++++++++++++++- 6 files changed, 1147 insertions(+), 106 deletions(-) diff --git a/extensions/llm-helper/README.md b/extensions/llm-helper/README.md index 826ffea..60fa0b9 100644 --- a/extensions/llm-helper/README.md +++ b/extensions/llm-helper/README.md @@ -99,7 +99,7 @@ token batches as they are produced. | `attachments` | `llm.chat` only, and never a loop turn. Files for the model to look at, named by reference: a non-empty list whose entries are a path inside `llm.attachments.root`, or `{path, pages}` for pages of a PDF, such as `13` or `1-3,7`. See Attachments. | | `params.model` | The model. Default `claude-opus-5-5` (`llm.model`). On Bedrock's default surface a bare id is sent with the `anthropic.` prefix and an id already spelled for Bedrock as written; on the classic runtime surface every id is sent as written, an inference profile id as the account lists it. | | `params.max_tokens` | Output cap. Default 16000 (`llm.max.tokens`). | -| `params.timeout_ms` | `llm.chat`: a deadline for the whole call, SDK retries included. `llm.stream`: the idle allowance between events. Default 60000 (`llm.timeout.ms`). | +| `params.timeout_ms` | `llm.chat`: a deadline for the whole call, SDK retries included. `llm.stream`: the idle allowance between events. Default 60000 (`llm.timeout.ms`), at most 2147483647. | | `params.effort` | `low`, `medium`, `high`, `xhigh` or `max`. Sent only when set; otherwise the model's own default applies. A model that takes no effort parameter answers 400. | | `params.stop_sequences` | A list of strings. | | `params.provider` | Accepted for compatibility: only `anthropic`. | @@ -112,9 +112,19 @@ sampling parameters (`temperature`, `top_p`, `top_k`), so none is forwarded. value (`16000`, or `16000.0`, which one runtime cannot tell from it) or a string of the ASCII digits 0 to 9 (`"16000"`), up to 9007199254740991, the largest whole number both runtimes hold exactly; a whole-number key of the configuration is read as such a string. A duration is such a number of -seconds, or ASCII digits and one unit (`30m`, `12h`, `2d`). White space around it is ignored. -Anything else - a fraction, a sign, an underscore, the digits of another script - is a 400 that -names the field or the key. +seconds, or ASCII digits and one unit (`30m`, `12h`, `2d`). White space - the 24 characters both +runtimes' own trim takes: tab to carriage return, the space, the no-break space and the other +space separators, the line and the paragraph separator - is ignored around a number and never +inside one: in `pages` around each page number, so `1 - 3 , 7` is `1-3,7`, and `1 3` is not page +13 but a 400. Anything else - a fraction, a sign, an underscore, the digits of another script - +is refused by the name of the field or the key: a field of a request with a 400, a key of the +configuration when the helper starts (see Configuration). + +**A time in milliseconds has a maximum.** `params.timeout_ms`, `llm.timeout.ms`, +`llm.transcript.audit.sweep.ms` and the two stores' `timeout.ms` take at most 2147483647, about +24.8 days: the longest wait the timers of both runtimes hold (Node.js fires a longer one at +once) and the longest `statement_timeout` PostgreSQL takes. A longer one is refused like a value +that is no number. **`llm.chat` reply** (a map): `text`, or `data` for a `schema` request; `model` (the model that answered); `stop_reason`; `usage {input_tokens, output_tokens}`; `request_id` when the API sent one; @@ -221,7 +231,7 @@ still answers: guard the node with a decision on the reference when the page is | Case | Status | |---|---| | `attachments` on `llm.stream`, or on a loop turn; a last turn that is not the user's | 400 | -| Not a non-empty list; an entry that is neither a path nor `{path, pages}`; `pages` that are malformed, run backward or name a page twice | 400 | +| Not a non-empty list; an entry that is neither a path nor `{path, pages}`; a path that is empty or only white space, by the white space of the number rule; `pages` that are malformed, run backward or name a page twice | 400 | | More files than `llm.attachments.max.count`, or more bytes of files than `llm.attachments.max.bytes` (taken from each file's size before it is read) | 400 | | An absolute path, a path or a link that leads out of the folder, a hidden entry, a missing file, a folder | 400 | | A file that is not PNG, JPEG, GIF, WebP or PDF; `pages` on an image; a page the document does not have; an encrypted or unreadable PDF | 400 | @@ -229,6 +239,7 @@ still answers: guard the node with a decision on the reference when the page is | No `llm.attachments.root` configured | 503 | | `pages` without the `documents` extra | 503, naming the extra | | A configured `llm.attachments.root` that is not a folder | the application stops at start (a request that meets it later is a 500) | +| `llm.attachments.max.count` or `llm.attachments.max.bytes` that is not a whole number of 1 or more | the application stops at start (a request that meets it later is a 400) | **Limits that are the provider's.** The helper sends no more than 20 files by default because a request with more than 20 image and document blocks is held to a tighter limit on each image's dimensions. A request takes at most 600 @@ -350,7 +361,9 @@ output_tokens, cache_creation_input_tokens, cache_read_input_tokens}` and `reque ### The transcript store `llm.transcript.store` names it, and a loop turn without one is a `503 transcript store not configured`. A request -without `tools` never touches it, unless single calls are audited (see The audit of a single call). +without `tools` never touches it, unless single calls are audited (see The audit of a single call). A name that is +neither of the two below stops the application at start, by name, and so does `redis` whose client is not installed +or whose connection keys are wrong. | `llm.transcript.store` | For | |---|---| @@ -360,9 +373,9 @@ without `tools` never touches it, unless single calls are audited (see The audit Redis keeps one hash per conversation under `transcript:{conversation}`, holding the turn count and the record. A Lua script makes the compare-and-set atomic on that one key. A deployment may share one Redis with the graph's suspend store (`minigraph-state-redis`, keys `graph:{graph_id}:{cid}`): give this app a Redis ACL user confined to -`~transcript:*`, so the two share a server but neither a namespace nor a credential. The client connects on the -first turn, to a standalone server (a cluster's configuration endpoint needs the cluster client, not built yet); a -store that cannot be reached is a `503 transcript store unreachable - …`. +`~transcript:*`, so the two share a server but neither a namespace nor a credential. The client is built at start +and connects on the first turn, to a standalone server (a cluster's configuration endpoint needs the cluster +client, not built yet); a store that cannot be reached is a `503 transcript store unreachable - …`. Every write sets the record's time to live to `ttl`, so a run that waits for a person keeps its transcript: make `ttl` at least as long as the longest approval wait. When the model ends the run (done, a refusal, the context @@ -430,10 +443,10 @@ for the save; a working store that fails is logged by type, and that call is not prompt and reply, kept for `llm.transcript.audit.retention`. **Retention and purge are the installation's.** `expires_at` is written as the first turn's start plus -`llm.transcript.audit.retention` (default `365d`); the helper runs no purge. `schema/purge.sql` holds the two -statements a purge is, `dev/audit-purge.sh` runs them against the development container by hand (`--dry-run` counts, -`--before ` also removes the conversations started before it), and operations automate the same statements on -the enterprise's own schedule and policy. +`llm.transcript.audit.retention` (default `365d`, at most `1000000d`); the helper runs no purge. `schema/purge.sql` +holds the two statements a purge is, `dev/audit-purge.sh` runs them against the development container by hand +(`--dry-run` counts, `--before ` also removes the conversations started before it), and operations automate +the same statements on the enterprise's own schedule and policy. **Development.** `dev/postgres-up.sh` runs PostgreSQL 17 with the schema applied at first start and pgweb as the SQL browser at `http://127.0.0.1:8081`, on Colima or Docker, `POSTGRES_PASSWORD` from the environment; @@ -455,6 +468,21 @@ installation's, applied on read. `resources/application.yml`, or `-Dkey=value` at run time. A call's `params` win over these keys. +**A setting that is wrong stops the application when it starts.** Every key below that can be wrong is read at +start, before a request finds it: a number or a duration that is not one or is out of its range, a name that is not +one of those listed, a switch that is neither `true` nor `false`, a transcript or an audit store whose client is not +installed. One ERROR line says what is wrong - `llm.helper cannot start - llm.max.tokens must be a whole +number >= 1`, or `attachments cannot start - ...` and `transcript audit store cannot start - ...` for those two +features - and the application stops. The keys of a feature that is not configured are not read: the +`llm.transcript.redis.*` keys without `llm.transcript.store: redis`, the `llm.transcript.audit.*` keys without +`llm.transcript.audit`, `llm.aws.api` without `llm.backend: bedrock`. A call's own `params` are not settings and keep +their 400 on the call; a credential, a region and a store that does not answer are found when a call is made. + +**A switch is `true` or `false`.** `llm.log.batches`, `llm.transcript.audit.single`, `llm.transcript.redis.ssl` and +`llm.transcript.audit.postgres.ssl` take the boolean, or the text `true` or `false` in any letter case; a key that +is unset or empty is its default. Any other value the helper is given - `-Dllm.log.batches=1`, a quoted `'maybe'` - +stops the application at start, by name: it is never read as off. + | Key | Default | Meaning | |---|---|---| | `llm.backend` | `anthropic` | The route to the models: `anthropic` (the Claude API) or `bedrock` (AWS Bedrock); see Backends. | @@ -462,25 +490,25 @@ installation's, applied on read. | `llm.aws.api` | `mantle` | The Bedrock surface: `mantle`, the Anthropic-shaped endpoint, or `runtime`, the classic one; see Backends. | | `llm.model` | `claude-opus-5-5` | The default model. | | `llm.max.tokens` | `16000` | The default output cap. | -| `llm.timeout.ms` | `60000` | The default deadline (chat) or idle allowance (stream). | +| `llm.timeout.ms` | `60000` | The default deadline (chat) or idle allowance (stream). At most 2147483647. | | `llm.max.retries` | `2` | SDK retries for connection errors, 408, 409, 429 and 5xx. | | `llm.fallbacks` | `default` | `default` or `off`. Server-side refusal fallbacks (`fallbacks: "default"`) on the models that support them (the Opus 5, Fable 5 and Sonnet 5.5 families). The reply's `model` names the model that answered. The Claude API only: Bedrock offers none, so the switch has no effect there. | | `llm.effort` | unset | The default effort. | | `llm.log.batches` | `false` | Log each streamed batch's number, size and arrival time (never its text). | -| `llm.provider` | `anthropic` | Only `anthropic`; any other value is a 400. | +| `llm.provider` | `anthropic` | Only `anthropic`; any other value stops the application at start, and a call's `params.provider` that names another is a 400. | | `llm.attachments.root` | unset | The one folder whose files a request may name in `attachments` (see Attachments). Unset, every attachment is a 503. | -| `llm.attachments.max.count` | `20` | Files per call. | -| `llm.attachments.max.bytes` | `20971520` | Bytes of files per call (20 MB), counted from the files' sizes before they are read. | +| `llm.attachments.max.count` | `20` | Files per call, 1 or more. | +| `llm.attachments.max.bytes` | `20971520` | Bytes of files per call (20 MB), counted from the files' sizes before they are read; 1 or more. | | `llm.transcript.store` | unset | `memory` or `redis`; a loop turn needs one (see The transcript store). | | `llm.transcript.ttl` | `7d` | A loop turn's `ttl` when the request carries none. | | `llm.transcript.retention` | `0` | A loop turn's `retention` when the request carries none. | -| `llm.transcript.redis.host`, `.port`, `.username`, `.password`, `.ssl`, `.database`, `.timeout.ms` | `127.0.0.1`, `6379`, none, none, `false`, `0`, `5000` | The Redis connection: the engines' `redis.*` set under this store's own prefix. The password comes from the environment (`${REDIS_PASSWORD}`). | +| `llm.transcript.redis.host`, `.port`, `.username`, `.password`, `.ssl`, `.database`, `.timeout.ms` | `127.0.0.1`, `6379`, none, none, `false`, `0`, `5000` | The Redis connection: the engines' `redis.*` set under this store's own prefix. The password comes from the environment (`${REDIS_PASSWORD}`). `port` is at most 65535 and `timeout.ms` at most 2147483647. | | `llm.transcript.audit` | unset | `postgres`: record every model turn in the audit store (see The audit store). Unset, no audit. | -| `llm.transcript.audit.retention` | `365d` | Written as a conversation's `expires_at`; the purge is the installation's. A value that is not a duration stops the application at start, by name. | +| `llm.transcript.audit.retention` | `365d` | Written as a conversation's `expires_at`; the purge is the installation's. At most `1000000d`: with it the date keeps a four-digit year, which both packs and the database write the same way. A value that is not a duration, or a longer one, stops the application at start, by name. | | `llm.transcript.audit.grace` | `1d` | How long a closed working record waits for its integrity check before it expires unreleased. A value that is not a duration of a second or more stops the application at start, by name. | -| `llm.transcript.audit.sweep.ms` | `60000` | The sweep that repairs lost events and stopped runs; `0` disables it. | +| `llm.transcript.audit.sweep.ms` | `60000` | The sweep that repairs lost events and stopped runs; `0` disables it. At most 2147483647. | | `llm.transcript.audit.single` | `false` | `true`: record a call without `tools` as a conversation of one turn (see The audit of a single call). Needs `llm.transcript.store`. | -| `llm.transcript.audit.postgres.host`, `.port`, `.database`, `.username`, `.password`, `.ssl`, `.timeout.ms` | `127.0.0.1`, `5432`, `mercury`, none, none, `true`, `5000` | The PostgreSQL connection, the engines' convention under this store's prefix. The shipped `application.yml` sets the user and the password from the environment (`${POSTGRES_USER:mercury}`, `${POSTGRES_PASSWORD}`); `ssl` `true` is `sslmode=require`, `false` `sslmode=disable`; `timeout.ms` bounds a connection attempt, a wait for the pool and, on the server, a statement (`statement_timeout`). | +| `llm.transcript.audit.postgres.host`, `.port`, `.database`, `.username`, `.password`, `.ssl`, `.timeout.ms` | `127.0.0.1`, `5432`, `mercury`, none, none, `true`, `5000` | The PostgreSQL connection, the engines' convention under this store's prefix. The shipped `application.yml` sets the user and the password from the environment (`${POSTGRES_USER:mercury}`, `${POSTGRES_PASSWORD}`); `ssl` `true` is `sslmode=require`, `false` `sslmode=disable`; `timeout.ms` bounds a connection attempt, a wait for the pool and, on the server, a statement (`statement_timeout`). `port` is at most 65535 and `timeout.ms` at most 2147483647. | The credential is never configured here. `ANTHROPIC_API_KEY` (or whatever the SDK resolves: an auth token, or a profile) comes from the environment for the Claude API; the AWS credential chain, @@ -560,9 +588,11 @@ by reference; it still decides nothing about control flow. ## Tests `tests/test_llm_helper.py` runs the shared `tests/vectors/llm-helper-vectors.json` against a fake of -the SDK (68 cases: request validation, the exact SDK call, replies, the error contract, streaming, -the shape of a Bedrock call on either surface; and 98 values under `numbers`, each read as a whole -number, as a duration and as the pages of a PDF, with the one answer both packs give) and the shared +the SDK (70 cases: request validation, the exact SDK call, replies, the error contract, streaming, +the shape of a Bedrock call on either surface; 101 values under `numbers`, each read as a whole +number, as a duration and as the pages of a PDF; 22 values under `switches`, each read as a switch +of the configuration; and 47 cases under `start`, each a configuration that a start-up step +passes or stops by name - all with the one answer both packs give) and the shared `tests/vectors/llm-loop-vectors.json` (66 cases of one or more turns: the loop fields, the exact SDK call of each turn with the transcript sent back, the reply, and the stored record after each step), the loop cases once on the memory store and again on a Redis fake that runs the @@ -582,7 +612,7 @@ beside it pin that the reply does not wait for the save, that a failed write is loop turn is untouched by the switch. `tests/test_llm_attachments.py` pins the attachments with a third shared file, -`tests/vectors/llm-attachments-vectors.json` (48 cases: the shape of the field, where it does not belong, the folder +`tests/vectors/llm-attachments-vectors.json` (52 cases: the shape of the field, where it does not belong, the folder a request stays inside, the files refused before any model call, the blocks the model gets, the reference the audit keeps), over the fixture files of `tests/fixtures/attachments`, which both packs hold byte for byte. A cut PDF is checked page by page and never byte for byte, since two PDF libraries do not write the same bytes. The tests beside it diff --git a/extensions/llm-helper/llm_helper.py b/extensions/llm-helper/llm_helper.py index e807d51..371c2a1 100644 --- a/extensions/llm-helper/llm_helper.py +++ b/extensions/llm-helper/llm_helper.py @@ -89,6 +89,12 @@ DEFAULT_MAX_TOKENS = 16000 DEFAULT_TIMEOUT_MS = 60000 DEFAULT_MAX_RETRIES = 2 +# the settings a request falls back on: read on a request and when the helper starts, where a +# refusal names the key +_MAX_TOKENS_KEY = "llm.max.tokens" +_TIMEOUT_KEY = "llm.timeout.ms" +_MAX_RETRIES_KEY = "llm.max.retries" +_EFFORT_KEY = "llm.effort" PROVIDERS = (DEFAULT_PROVIDER,) BACKENDS = (DEFAULT_BACKEND, BEDROCK_BACKEND) # the Anthropic-shaped surface spells a model id with the vendor prefix; a bare id gets it, a @@ -122,13 +128,18 @@ # the largest whole number both packs hold exactly (2**53 - 1): above it the Node.js twin's # numbers round, and the twins would read two different numbers from one request MAX_WHOLE = 9007199254740991 -# the white space ignored around a number, and anywhere in pages: the characters Python's -# str.strip() and JavaScript's trim() both take for white space, so neither pack accepts a -# character the other refuses +# the longest wait both packs' timers hold, in milliseconds (2**31 - 1, about 24.8 days): the +# Node.js twin's timers keep a delay in 32 bits with a sign and fire at once on a longer one +MAX_TIMER_MS = 2147483647 +# the highest port a connection can name +MAX_PORT = 65535 +# the white space ignored around a number - in pages around each number, never inside one - and +# the white space a path is not made of: the characters Python's str.strip() and JavaScript's +# trim() both take for white space, so neither pack accepts a character the other refuses _SPACE = r"[\t-\r \xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]" _SPACES = re.compile(f"{_SPACE}+") # the digits 0 to 9 and no other, by flag: Python's own \d takes the digits of every script, the -# Node.js twin's these ten - the patterns of a duration and of pages ask for them the same way +# Node.js twin's these ten - the pattern of a duration asks for them the same way WHOLE = re.compile(rf"{_SPACE}*(\d+){_SPACE}*", re.ASCII) # --- the loop contract's defaults and limits (RFC-0011) ----------------------------------- @@ -144,6 +155,8 @@ DURATION_SECONDS = {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400} DEFAULT_TRANSCRIPT_TTL = "7d" DEFAULT_TRANSCRIPT_RETENTION = "0" +_TRANSCRIPT_TTL_KEY = "llm.transcript.ttl" +_TRANSCRIPT_RETENTION_KEY = "llm.transcript.retention" # the configuration key that names the transcript store, one of STORES _TRANSCRIPT_STORE_KEY = "llm.transcript.store" STORE_MEMORY = "memory" @@ -174,8 +187,8 @@ # image's dimension limit DEFAULT_ATTACHMENTS_MAX_COUNT = 20 DEFAULT_ATTACHMENTS_MAX_BYTES = 20 * 1024 * 1024 +_READ_PIECE = 1024 * 1024 # a file is read a mebibyte at a time ATTACHMENT_KEYS = ("path", "pages") -PAGES = re.compile(r"\d+(-\d+)?(,\d+(-\d+)?)*", re.ASCII) PDF_MEDIA_TYPE = "application/pdf" # an image's limit as the provider counts it, base64-encoded: by the route to the models IMAGE_MAX_ENCODED = 10 * 1024 * 1024 @@ -197,6 +210,9 @@ AUDIT_POSTGRES = "postgres" AUDITS = (AUDIT_POSTGRES,) DEFAULT_AUDIT_RETENTION = "365d" +# the longest audit retention, a million days in seconds: with it a conversation's expires_at is +# a date of a four-digit year, which both packs and the database write the same way +MAX_AUDIT_RETENTION_S = 1_000_000 * 86400 DEFAULT_AUDIT_GRACE = "1d" DEFAULT_AUDIT_SWEEP_MS = 60000 # the sweep's lock on Redis, under the store's prefix so one ACL covers it; never a conversation key @@ -275,16 +291,37 @@ def _whole(digits: str) -> int | None: return number if number <= MAX_WHOLE else None -def _whole_number(name: str, value: Any, minimum: int) -> int: - """A whole number from a JSON number or a config string, or a 400 naming the field.""" - text = _number_text(value) +def _spelled(text: str | None) -> int | None: + """The whole number a text spells - ASCII digits, the white space around them ignored and + none allowed between them - or None.""" match = WHOLE.fullmatch(text) if text is not None else None - number = _whole(match.group(1)) if match else None - if number is None or number < minimum: + return _whole(match.group(1)) if match else None + + +def _whole_number(name: str, value: Any, minimum: int, maximum: int = MAX_WHOLE) -> int: + """A whole number from a JSON number or a config string, or a 400 naming the field. A + number that sets a timer or names a port has a maximum of its own, refused the same way.""" + number = _spelled(_number_text(value)) + if number is None or not minimum <= number <= maximum: raise AppException(400, f"{name} must be a whole number >= {minimum}") return number +def _switch(key: str, default: bool) -> bool: + """A switch of the configuration: true or false, the boolean or the text in any letter + case; no value and an empty one are the default. Any other value would be read as off + without a word - TLS written "yes" would be no TLS - so it is refused by name.""" + value: Any = _prop(key) + if value is None or value == "": + return default + if isinstance(value, bool): + return value + lowered = value.lower() if isinstance(value, str) else "" + if lowered not in ("true", "false"): + raise AppException(500, f"{key} must be true or false") + return lowered == "true" + + def _setting(params: dict[str, Any], key: str, config_key: str, default: str) -> Any: """Precedence: the call's param, then the config key, then the built-in default.""" value = params.get(key) @@ -337,14 +374,18 @@ def _system(body: dict[str, Any]) -> str | None: return system or None -def _effort(params: dict[str, Any]) -> str | None: - effort = params.get("effort") or _prop("llm.effort") +def _effort_level(name: str, effort: Any) -> str | None: + """An effort the models take, in lower case, or a 400 naming the field or the setting.""" if effort is None: return None - effort = str(effort).lower() - if effort not in EFFORTS: - raise AppException(400, f"params.effort must be one of: {', '.join(EFFORTS)}") - return effort + level = str(effort).lower() + if level not in EFFORTS: + raise AppException(400, f"{name} must be one of: {', '.join(EFFORTS)}") + return level + + +def _effort(params: dict[str, Any]) -> str | None: + return _effort_level("params.effort", params.get("effort") or _prop(_EFFORT_KEY)) def _stop_sequences(params: dict[str, Any]) -> list[str] | None: @@ -370,26 +411,26 @@ def _schema(body: dict[str, Any], streaming: bool) -> dict[str, Any] | None: def _pages(index: int, raw: Any) -> tuple[tuple[tuple[int, int], ...], str]: """The pages of a PDF to send, as ranges in the order named, with the text as written. A - mapping may carry a page number as a number. Whether a page exists is the document's to say, - when it is read.""" + mapping may carry a page number as a number. White space is ignored around a number - so + around a comma and a hyphen - and never inside one: "1 3" names no page. Whether a page + exists is the document's to say, when it is read.""" text = _number_text(raw) - if text is not None: - text = _SPACES.sub("", text) malformed = AppException( 400, f"attachments[{index}].pages must name pages from 1, such as 13 or 1-3,7" ) - if text is None or not PAGES.fullmatch(text): + if text is None: raise malformed ranges: list[tuple[int, int]] = [] for part in text.split(","): - first, _, last = part.partition("-") - low, high = _whole(first), _whole(last or first) + first, hyphen, last = part.partition("-") + low = _spelled(first) + high = _spelled(last) if hyphen else low if low is None or high is None or low < 1 or high < low: raise malformed if any(low <= held_high and held_low <= high for held_low, held_high in ranges): raise AppException(400, f"attachments[{index}].pages names a page twice") ranges.append((low, high)) - return tuple(ranges), text + return tuple(ranges), _SPACES.sub("", text) def _attachment(index: int, entry: Any) -> Attachment: @@ -408,7 +449,8 @@ def _attachment(index: int, entry: Any) -> Attachment: path, pages = entry.get("path"), entry.get("pages") else: raise AppException(400, f"attachments[{index}] must be a path or {{path, pages}}") - if not isinstance(path, str) or not path.strip(): + # blank by the white space of the number rule, so both packs call the same paths blank + if not isinstance(path, str) or not _SPACES.sub("", path): raise AppException( 400, f"attachments[{index}].path must be a path inside {ATTACHMENTS_ROOT}" ) @@ -418,6 +460,22 @@ def _attachment(index: int, entry: Any) -> Attachment: return Attachment(path, ranges, text) +def _attachments_max_count() -> int: + return _whole_number( + ATTACHMENTS_MAX_COUNT, + _prop(ATTACHMENTS_MAX_COUNT, str(DEFAULT_ATTACHMENTS_MAX_COUNT)), + 1, + ) + + +def _attachments_max_bytes() -> int: + return _whole_number( + ATTACHMENTS_MAX_BYTES, + _prop(ATTACHMENTS_MAX_BYTES, str(DEFAULT_ATTACHMENTS_MAX_BYTES)), + 1, + ) + + def _attachments(body: dict[str, Any]) -> tuple[Attachment, ...]: """The files a single call names (RFC-0016): the shape only. The files themselves are read by attach(), after every other check of the request has passed.""" @@ -426,11 +484,7 @@ def _attachments(body: dict[str, Any]) -> tuple[Attachment, ...]: return () if not isinstance(raw, list) or not raw: raise AppException(400, ATTACHMENTS_SHAPE) - limit = _whole_number( - ATTACHMENTS_MAX_COUNT, - _prop(ATTACHMENTS_MAX_COUNT, str(DEFAULT_ATTACHMENTS_MAX_COUNT)), - 1, - ) + limit = _attachments_max_count() if len(raw) > limit: raise AppException( 400, f"attachments: {len(raw)} files exceed {ATTACHMENTS_MAX_COUNT} ({limit})" @@ -467,16 +521,17 @@ def prepare(body: Body, *, streaming: bool, continuation: bool = False) -> LlmRe model = str(_setting(params, "model", "llm.model", DEFAULT_MODEL)) max_tokens = _whole_number( "params.max_tokens", - _setting(params, "max_tokens", "llm.max.tokens", str(DEFAULT_MAX_TOKENS)), + _setting(params, "max_tokens", _MAX_TOKENS_KEY, str(DEFAULT_MAX_TOKENS)), 1, ) timeout_ms = _whole_number( "params.timeout_ms", - _setting(params, "timeout_ms", "llm.timeout.ms", str(DEFAULT_TIMEOUT_MS)), + _setting(params, "timeout_ms", _TIMEOUT_KEY, str(DEFAULT_TIMEOUT_MS)), 1, + MAX_TIMER_MS, ) max_retries = _whole_number( - "llm.max.retries", _prop("llm.max.retries", str(DEFAULT_MAX_RETRIES)), 0 + _MAX_RETRIES_KEY, _prop(_MAX_RETRIES_KEY, str(DEFAULT_MAX_RETRIES)), 0 ) return LlmRequest( model=model, @@ -596,13 +651,14 @@ def _results(raw: Any) -> list[dict[str, Any]] | None: return raw -def _duration(name: str, value: Any, minimum: int) -> int: - """Seconds from a whole number or a duration such as 30m, 12h or 2d, or a 400 naming it.""" +def _duration(name: str, value: Any, minimum: int, maximum: int = MAX_WHOLE) -> int: + """Seconds from a whole number or a duration such as 30m, 12h or 2d, or a 400 naming it. A + duration that becomes a date has a maximum of its own, refused the same way.""" text = _number_text(value) match = DURATION.fullmatch(text) if text is not None else None count = _whole(match.group(1)) if match else None seconds = -1 if match is None or count is None else count * DURATION_SECONDS[match.group(2)] - if not minimum <= seconds <= MAX_WHOLE: + if not minimum <= seconds <= maximum: raise AppException( 400, f"{name} must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= {minimum}", @@ -626,10 +682,10 @@ def prepare_loop(body: dict[str, Any]) -> LoopTurn: results = _results(body.get("results")) ttl = body.get("ttl") if ttl is None: - ttl = _prop("llm.transcript.ttl", DEFAULT_TRANSCRIPT_TTL) + ttl = _prop(_TRANSCRIPT_TTL_KEY, DEFAULT_TRANSCRIPT_TTL) retention = body.get("retention") if retention is None: - retention = _prop("llm.transcript.retention", DEFAULT_TRANSCRIPT_RETENTION) + retention = _prop(_TRANSCRIPT_RETENTION_KEY, DEFAULT_TRANSCRIPT_RETENTION) ttl_s = _duration("ttl", ttl, 1) retention_s = _duration("retention", retention, 0) _check_turn_shape(body, conversation, turn, results) @@ -768,15 +824,21 @@ def _bedrock_client(aws_api: str) -> Any: raise AppException(503, MISSING_AWS_REGION) from exc +def _backend_name() -> str: + """The route to the models the configuration names, or a 501 that names the ones served.""" + name = str(_prop("llm.backend", DEFAULT_BACKEND) or DEFAULT_BACKEND).lower() + if name not in BACKENDS: + raise AppException( + 501, f"unknown LLM backend '{name}' - this helper serves: {', '.join(BACKENDS)}" + ) + return name + + def get_backend() -> Backend: global _backend backend = _backend if backend is None: - name = str(_prop("llm.backend", DEFAULT_BACKEND) or DEFAULT_BACKEND).lower() - if name not in BACKENDS: - raise AppException( - 501, f"unknown LLM backend '{name}' - this helper serves: {', '.join(BACKENDS)}" - ) + name = _backend_name() # credentials resolve per call, so the app starts (and reports its health) without one aws_api = _aws_api() if name == BEDROCK_BACKEND else AWS_API_MANTLE client = _bedrock_client(aws_api) if name == BEDROCK_BACKEND else anthropic.AsyncAnthropic() @@ -959,6 +1021,22 @@ def _check_image( ) +def _read_up_to(handle: io.BufferedReader, limit: int) -> bytes: + """At most ``limit`` bytes of an open file, a piece at a time, as the Node.js twin reads it: + a file may grow under the read, and one read of the whole allowance would ask for that much + memory at once whatever the file's size - a MemoryError under a very large + llm.attachments.max.bytes.""" + pieces: list[bytes] = [] + held = 0 + while held < limit: + piece = handle.read(min(limit - held, _READ_PIECE)) + if not piece: + break + pieces.append(piece) + held += len(piece) + return b"".join(pieces) + + def _load_attachments( specs: tuple[Attachment, ...], root: Path, max_bytes: int, image_max_encoded: int ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], int]: @@ -976,7 +1054,7 @@ def _load_attachments( if total + file.stat().st_size > max_bytes: raise AppException(400, over.format(max_bytes, ATTACHMENTS_MAX_BYTES, max_bytes)) with file.open("rb") as handle: - data = handle.read(max_bytes - total + 1) # bounded: a file may grow under the read + data = _read_up_to(handle, max_bytes - total + 1) total += len(data) if total > max_bytes: raise AppException(400, over.format(max_bytes, ATTACHMENTS_MAX_BYTES, max_bytes)) @@ -1021,11 +1099,7 @@ async def attach(request: LlmRequest, backend: Backend) -> Attached: if last["role"] != "user": raise AppException(400, "attachments go with the last turn, which must be the user's") root = attachments_root() - max_bytes = _whole_number( - ATTACHMENTS_MAX_BYTES, - _prop(ATTACHMENTS_MAX_BYTES, str(DEFAULT_ATTACHMENTS_MAX_BYTES)), - 1, - ) + max_bytes = _attachments_max_bytes() blocks, references, size = await asyncio.to_thread( _load_attachments, request.attachments, root, max_bytes, backend.image_max_encoded ) @@ -1040,16 +1114,19 @@ async def attach(request: LlmRequest, backend: Backend) -> Attached: async def attachments_boot() -> None: # NOSONAR - async by contract: the host awaits it at startup - """A root that is configured and is not a folder is a deployment error: stop by name at - start, before a request finds it.""" - if not _prop(ATTACHMENTS_ROOT): - return + """A limit that is not a whole number, and a root that is configured and is not a folder, + is a deployment error: stop by name at start, before a request finds it.""" + configured = bool(_prop(ATTACHMENTS_ROOT)) try: - attachments_root() + _attachments_max_count() + _attachments_max_bytes() + if configured: + attachments_root() except AppException as exc: log.error("attachments cannot start - %s", exc.message) raise SystemExit(1) from exc - log.info("attachments ready - %s is set", ATTACHMENTS_ROOT) + if configured: + log.info("attachments ready - %s is set", ATTACHMENTS_ROOT) # --- one provider call, shared by both routes ------------------------------------------ @@ -1513,18 +1590,21 @@ def _redis_store() -> RedisStore: timeout_s = ( _whole_number( - "llm.transcript.redis.timeout.ms", _prop("llm.transcript.redis.timeout.ms", "5000"), 1 + "llm.transcript.redis.timeout.ms", + _prop("llm.transcript.redis.timeout.ms", "5000"), + 1, + MAX_TIMER_MS, ) / 1000 ) client = redis_async.Redis( host=str(_prop("llm.transcript.redis.host", "127.0.0.1")), port=_whole_number( - "llm.transcript.redis.port", _prop("llm.transcript.redis.port", "6379"), 1 + "llm.transcript.redis.port", _prop("llm.transcript.redis.port", "6379"), 1, MAX_PORT ), username=_prop("llm.transcript.redis.username") or None, password=_prop("llm.transcript.redis.password") or None, - ssl=str(_prop("llm.transcript.redis.ssl", "false")).lower() == "true", + ssl=_switch("llm.transcript.redis.ssl", False), db=_whole_number( "llm.transcript.redis.database", _prop("llm.transcript.redis.database", "0"), 0 ), @@ -2000,12 +2080,14 @@ def _postgres_audit_store() -> PostgresAuditStore: from psycopg_pool import AsyncConnectionPool # the [postgres] extra; checked above prefix = "llm.transcript.audit.postgres." - timeout_ms = _whole_number(prefix + "timeout.ms", _prop(prefix + "timeout.ms", "5000"), 1) + timeout_ms = _whole_number( + prefix + "timeout.ms", _prop(prefix + "timeout.ms", "5000"), 1, MAX_TIMER_MS + ) timeout_s = timeout_ms / 1000 - ssl = str(_prop(prefix + "ssl", "true")).lower() == "true" + ssl = _switch(prefix + "ssl", True) settings: dict[str, Any] = { "host": str(_prop(prefix + "host", "127.0.0.1")), - "port": _whole_number(prefix + "port", _prop(prefix + "port", "5432"), 1), + "port": _whole_number(prefix + "port", _prop(prefix + "port", "5432"), 1, MAX_PORT), "dbname": str(_prop(prefix + "database", "mercury")), "user": _prop(prefix + "username") or None, "password": _prop(prefix + "password") or None, @@ -2060,6 +2142,7 @@ def _audit_retention_s() -> int: "llm.transcript.audit.retention", _prop("llm.transcript.audit.retention", DEFAULT_AUDIT_RETENTION), 0, + MAX_AUDIT_RETENTION_S, ) @@ -2068,6 +2151,7 @@ def _audit_sweep_ms() -> int: "llm.transcript.audit.sweep.ms", _prop("llm.transcript.audit.sweep.ms", str(DEFAULT_AUDIT_SWEEP_MS)), 0, + MAX_TIMER_MS, ) @@ -2104,7 +2188,7 @@ async def _notify_audit(conversation: str, turn: int, closed: bool) -> None: def audit_single_configured() -> bool: - return audit_configured() and str(_prop(AUDIT_SINGLE, "false")).lower() == "true" + return audit_configured() and _switch(AUDIT_SINGLE, False) def _single_status(stop_reason: str) -> str: @@ -2351,9 +2435,10 @@ async def _sweep_forever(interval_ms: int) -> None: async def audit_boot() -> None: """Start the audit when llm.transcript.audit is configured: register transcript.audit with one - instance, open the store and start the sweep. A driver that is not installed, and a grace or - a retention that is not a duration, stops the application by name (a deployment error); a - database that does not answer is logged, and the sweep repairs what the outage defers.""" + instance, open the store and start the sweep. A driver that is not installed, and a setting + of the audit that is wrong - its grace, its retention, its sweep, a switch, a connection key - + stops the application by name (a deployment error); a database that does not answer is + logged, and the sweep repairs what the outage defers.""" global _sweep_task if not audit_configured(): return @@ -2362,11 +2447,13 @@ async def audit_boot() -> None: # would surface after the model was called _audit_grace_s() _audit_retention_s() + sweep_ms = _audit_sweep_ms() + single = audit_single_configured() audit = get_audit_store() except AppException as exc: log.error("transcript audit store cannot start - %s", exc.message) raise SystemExit(1) from exc - if audit_single_configured() and not _prop(_TRANSCRIPT_STORE_KEY): + if single and not _prop(_TRANSCRIPT_STORE_KEY): # a single call's record waits in the working store for its check: a deployment error log.error("transcript audit store cannot start - %s", MISSING_SINGLE_STORE) raise SystemExit(1) @@ -2383,7 +2470,6 @@ async def audit_boot() -> None: "outage defers", audit.name, _audit_failure(exc), ) # fmt: skip - sweep_ms = _audit_sweep_ms() if sweep_ms > 0 and _sweep_task is None: _sweep_task = asyncio.get_running_loop().create_task( _sweep_forever(sweep_ms), name="transcript-audit-sweep" @@ -2403,6 +2489,42 @@ async def audit_shutdown() -> None: await audit.close() +# --- the start: a setting that is wrong stops the application before a request finds it --------- + + +def _check_settings() -> None: + """The settings a request falls back on, each read once under its own name, or an + AppException that names it. A request's own params are checked on the request, as before.""" + _check_provider({}) + if _backend_name() == BEDROCK_BACKEND: + _aws_api() + _whole_number(_MAX_TOKENS_KEY, _prop(_MAX_TOKENS_KEY, str(DEFAULT_MAX_TOKENS)), 1) + _whole_number(_TIMEOUT_KEY, _prop(_TIMEOUT_KEY, str(DEFAULT_TIMEOUT_MS)), 1, MAX_TIMER_MS) + _whole_number(_MAX_RETRIES_KEY, _prop(_MAX_RETRIES_KEY, str(DEFAULT_MAX_RETRIES)), 0) + _effort_level(_EFFORT_KEY, _prop(_EFFORT_KEY)) + _fallbacks_enabled() + _switch("llm.log.batches", False) + _duration(_TRANSCRIPT_TTL_KEY, _prop(_TRANSCRIPT_TTL_KEY, DEFAULT_TRANSCRIPT_TTL), 1) + _duration( + _TRANSCRIPT_RETENTION_KEY, + _prop(_TRANSCRIPT_RETENTION_KEY, DEFAULT_TRANSCRIPT_RETENTION), + 0, + ) + + +async def settings_boot() -> None: # NOSONAR - async by contract: the host awaits it at startup + """The helper's settings are read when it starts - the ones a request falls back on, and the + transcript store with its connection keys when one is named: a wrong one is a deployment + error and stops the application by name, before a request finds it.""" + try: + _check_settings() + if _prop(_TRANSCRIPT_STORE_KEY): + get_store() + except AppException as exc: + log.error("llm.helper cannot start - %s", exc.message) + raise SystemExit(1) from exc + + # --- the functions ----------------------------------------------------------------------- @@ -2444,6 +2566,8 @@ async def llm_chat(headers: dict[str, str], body: Body) -> dict[str, Any]: if isinstance(body, dict) and _is_loop(body): return await _loop_turn(headers, body) request = prepare(body, streaming=False) + # the switch, read before the model is called: a wrong one costs no token + single = audit_single_configured() started = time.perf_counter() started_at = iso_utc() try: @@ -2456,7 +2580,7 @@ async def llm_chat(headers: dict[str, str], body: Body) -> dict[str, Any]: raise log.warning("llm.chat failed - status=%d", failure.status) raise failure from exc - if audit_single_configured(): + if single: # before the reply is judged: a refusal, a cut-off reply and a reply that is a 422 below # were answered by the model and cost tokens, so they are recorded too. With attachments # the record keeps a reference to each file, never its bytes @@ -2502,6 +2626,9 @@ async def llm_stream(headers: dict[str, str], event: EventEnvelope) -> None: try: request = prepare(event.body, streaming=True) backend = get_backend() + # the switches, read before the model is called: a wrong one costs no token + single = audit_single_configured() + batch_log = _switch("llm.log.batches", False) except AppException as exc: out.fail(exc) return @@ -2512,7 +2639,6 @@ async def llm_stream(headers: dict[str, str], event: EventEnvelope) -> None: "my_correlation_id": headers.get("my_correlation_id"), } frames = 0 - batch_log = str(_prop("llm.log.batches", "false")).lower() == "true" def forward(text: str) -> None: nonlocal frames @@ -2529,7 +2655,7 @@ def forward(text: str) -> None: started_at = iso_utc() try: done = await _complete(request, backend, on_text=forward) - if audit_single_configured(): + if single: # a stream the model completed is a single call like any other (RFC-0015) _audit_single(headers, request, done, (started_at, iso_utc())) _judge(request, done, has_content=frames > 0) @@ -2643,6 +2769,8 @@ async def llm_health(headers: dict[str, str], _body: Body) -> Any: return "llm.helper is running fine" +# the settings first: a wrong one stops the start before the audit opens its store +platform.on_startup(settings_boot) # the audit starts inside the serving loop, before the first request, when it is configured platform.on_startup(audit_boot) platform.on_startup(attachments_boot) # a configured root that is not a folder stops the start diff --git a/tests/test_llm_attachments.py b/tests/test_llm_attachments.py index cd5883b..94bf818 100644 --- a/tests/test_llm_attachments.py +++ b/tests/test_llm_attachments.py @@ -42,7 +42,7 @@ _FIXTURES = _TESTS / "fixtures" / "attachments" _VECTORS = _TESTS / "vectors" / "llm-attachments-vectors.json" # the Node.js twin pins the same digests: change a file in both packs or in neither -_VECTORS_SHA256 = "06b0e85f7fa67c51eb9e63e0833d25a5e96f660c91210e460d3a346f2c574153" +_VECTORS_SHA256 = "3d76157645db836ad64388d969dfefb644e732e5233fe623a3f0c756e17c2c7e" _FIXTURES_SHA256 = { "damaged.pdf": "36a27d716a382936c825c5c3cb7bd7a2d38c0af35242d89b186b31faf2eb4ee1", "encrypted.pdf": "9f9e621bbe4dad963b3f5846b449dcc7424344335722c670e5d425efc7580dc7", @@ -200,6 +200,26 @@ async def test_an_image_over_the_backends_limit_is_refused_before_any_call( assert len(client.ledger.calls) == 1, "only the call that passed reached the provider" +async def test_a_file_is_read_in_pieces_whatever_the_limit( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """A file is read a piece at a time, as the Node.js twin reads it, so the largest limit the + configuration takes costs no more memory than the file: one read of the whole allowance + asked for it all at once, and every attachment was a 500.""" + root = _root(monkeypatch, tmp_path, {"page.png": "pixel.png"}) + config = {helper.ATTACHMENTS_ROOT: str(root), helper.ATTACHMENTS_MAX_BYTES: str(helper.MAX_WHOLE)} + _install_backend(monkeypatch, _FakeClient(_ANSWER), config) + assert (await helper.llm_chat({}, {"prompt": "x", "attachments": ["page.png"]}))["text"] == "A page." + # the reader itself: the whole file under a larger limit, and never more than the limit + piece = helper._READ_PIECE + content = bytes(range(256)) * (2 * piece // 256) + b"tail" + long_file = tmp_path / "long.bin" + long_file.write_bytes(content) + for limit in (0, 1, piece - 1, piece, piece + 1, len(content), len(content) + 1, helper.MAX_WHOLE): + with long_file.open("rb") as handle: + assert helper._read_up_to(handle, limit) == content[:limit], limit + + async def test_without_the_pdf_library_pages_are_a_503_and_a_whole_document_goes_as_it_is( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: diff --git a/tests/test_llm_helper.py b/tests/test_llm_helper.py index 1678112..09ba057 100644 --- a/tests/test_llm_helper.py +++ b/tests/test_llm_helper.py @@ -19,6 +19,7 @@ import logging import os import sys +from collections.abc import Callable from pathlib import Path from types import SimpleNamespace from typing import Any @@ -30,13 +31,13 @@ from anthropic.lib.bedrock import AsyncAnthropicBedrock, AsyncAnthropicBedrockMantle from anthropic.types import RedactedThinkingBlock, TextBlock, ThinkingBlock, ToolUseBlock -from mercury_composable import AppException +from mercury_composable import AppException, FunctionRegistry _TESTS = Path(__file__).resolve().parent _HELPER = _TESTS.parent / "extensions" / "llm-helper" / "llm_helper.py" _VECTORS = _TESTS / "vectors" / "llm-helper-vectors.json" # the Node.js twin pins the same digest: change the file in both packs or in neither -_VECTORS_SHA256 = "eff1bfef426d6ac815f9a14ffc8de962eeac1894cbef0015b517b61c42b20b78" +_VECTORS_SHA256 = "cda5392eb56599b3ad8f5a5942af3e12a87c5c29972ab4d963050ddc0fe330ca" _spec = importlib.util.spec_from_file_location("llm_helper_under_test", _HELPER) assert _spec is not None @@ -563,6 +564,126 @@ def test_pages_are_read_as_the_node_twin_reads_them( assert _exactly(answer) == _exactly(refused if wanted is None else wanted) +# --- the shared contract: how a switch of the configuration is read -------------------------- +# +# "switches" in llm-helper-vectors.json is one list of values and what each reads as: true, +# false, the switch's default, or nothing - a value that is refused by name instead of being +# read as off. + +SWITCHES: dict[str, Any] = VECTORS["switches"] +SWITCH_PROBES: list[dict[str, Any]] = SWITCHES["probes"] +_BOTH_STORES = {"llm.transcript.store": "redis", "llm.transcript.audit": "postgres"} + + +def _postgres_tls() -> bool: + """Whether the audit store's pool is built to connect with TLS.""" + return helper.get_audit_store()._pool.kwargs["sslmode"] == "require" + + +def _redis_tls() -> bool: + """Whether the transcript store's client is built to connect with TLS.""" + pool = helper.get_store()._client.connection_pool + return pool.connection_class.__name__ == "SSLConnection" + + +@pytest.mark.parametrize("probe", SWITCH_PROBES, ids=[probe["name"] for probe in SWITCH_PROBES]) +@pytest.mark.parametrize( + ("key", "default", "tls"), + [ + ("llm.transcript.audit.postgres.ssl", True, _postgres_tls), + ("llm.transcript.redis.ssl", False, _redis_tls), + ], + ids=["postgres", "redis"], +) +def test_a_switch_is_read_as_the_node_twin_reads_it( + key: str, default: bool, tls: Callable[[], bool], probe: dict[str, Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: # fmt: skip + """The TLS switch of each store, as the store it builds: TLS, none, or the refusal by name.""" + config: dict[str, Any] = dict(_BOTH_STORES) + if probe["value"] is not None: + config[key] = probe["value"] + monkeypatch.setattr(helper, "_prop", lambda name, fallback=None: config.get(name, fallback)) + monkeypatch.setattr(helper, "_store", None) + monkeypatch.setattr(helper, "_audit", None) + try: + answer: Any = tls() + except AppException as exc: + answer = [exc.status, exc.message] + wanted = default if probe["on"] == "default" else probe["on"] + refused = [500, SWITCHES["refusal"].format(name=key)] + assert _exactly(answer) == _exactly(refused if wanted is None else wanted) + + +async def test_a_switch_that_is_wrong_is_refused_before_the_model_is_called( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The start refuses a switch that is wrong. A call that still meets one - a setting changed + at run time - is a 500 by name on both routes, before any token is spent.""" + client = _FakeClient(_REPLY) + audited = {**_LOOP_CONFIG, "llm.transcript.audit": "postgres"} + _install_backend(monkeypatch, client, {**audited, "llm.transcript.audit.single": "yes"}) + with pytest.raises(AppException) as raised: + await helper.llm_chat({}, {"prompt": "x"}) + assert raised.value.status == 500 + assert raised.value.message == "llm.transcript.audit.single must be true or false" + out = _install_writer(monkeypatch) + await helper.llm_stream({}, _event({"prompt": "x"})) + assert out.error is not None + assert out.error.message == "llm.transcript.audit.single must be true or false" + _install_backend(monkeypatch, client, {"llm.log.batches": "on"}) + out = _install_writer(monkeypatch) + await helper.llm_stream({}, _event({"prompt": "x"})) + assert out.error is not None + assert out.error.status == 500 + assert out.error.message == "llm.log.batches must be true or false" + assert client.ledger.calls == [], "a wrong switch costs no model call" + + +# --- the shared contract: what stops the application when it starts --------------------------- +# +# "start" in llm-helper-vectors.json names, for each of the three start-up steps, settings that +# are wrong and settings that are not: a wrong one stops the application by name, in the step's +# own voice, where it used to be refused on the first request that needed it. + +START: dict[str, Any] = VECTORS["start"] +START_CASES: list[dict[str, Any]] = START["cases"] + + +async def _no_database(_store: Any, *_args: Any) -> None: + """The audit store's open and close without a database: a start that passes opens nothing.""" + + +@pytest.mark.parametrize("case", START_CASES, ids=[case["name"] for case in START_CASES]) +async def test_a_setting_that_is_wrong_stops_the_start_by_name( + case: dict[str, Any], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """A start-up step with the case's settings: it passes without a word, or it logs the + refusal in its own voice and stops the application.""" + config: dict[str, str] = case["config"] + monkeypatch.setattr(helper, "_prop", lambda key, fallback=None: config.get(key, fallback)) + for built in ("_store", "_audit", "_sweep_task", "_attachments_root"): + monkeypatch.setattr(helper, built, None) + # a registry of the test's own: a start that passes registers the audit function in it + monkeypatch.setattr(helper, "default_registry", FunctionRegistry()) + monkeypatch.setattr(helper.PostgresAuditStore, "open", _no_database) + monkeypatch.setattr(helper.PostgresAuditStore, "close", _no_database) + boot = getattr(helper, f"{case['boot']}_boot") + refused = case["refused"] + caplog.set_level(logging.ERROR) + try: + if refused is None: + await boot() + else: + with pytest.raises(SystemExit): + await boot() + finally: + await helper.audit_shutdown() + errors = [record.getMessage() for record in caplog.records if record.levelno >= logging.ERROR] + voiced = START["voices"][case["boot"]].format(message=refused) + assert errors == ([] if refused is None else [voiced]) + + # --- the loop turn: what a vector cannot pin ----------------------------------------------- @@ -795,6 +916,25 @@ def test_the_redis_store_without_redis_is_a_503_that_names_the_extra( assert "mercury-composable[redis]" in raised.value.message +async def test_the_redis_store_without_redis_stops_the_start_by_name( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The store is built when the helper starts, so a client that is not installed is found + then, as the audit store's driver is, and not on the first loop turn.""" + monkeypatch.setattr(helper, "_store", None) + monkeypatch.setattr( + helper, + "_prop", + lambda key, default=None: "redis" if key == "llm.transcript.store" else default, + ) + monkeypatch.setattr(helper.importlib.util, "find_spec", lambda _name: None) + caplog.set_level(logging.ERROR) + with pytest.raises(SystemExit): + await helper.settings_boot() + errors = [record.getMessage() for record in caplog.records if record.levelno >= logging.ERROR] + assert errors == [f"llm.helper cannot start - {helper.MISSING_REDIS_SDK}"] + + @pytest.mark.skipif( not os.environ.get("LLM_TRANSCRIPT_REDIS_URL"), reason="a live Redis: set LLM_TRANSCRIPT_REDIS_URL, e.g. redis://127.0.0.1:6379/15", diff --git a/tests/vectors/llm-attachments-vectors.json b/tests/vectors/llm-attachments-vectors.json index b3d9e14..ee6c7db 100644 --- a/tests/vectors/llm-attachments-vectors.json +++ b/tests/vectors/llm-attachments-vectors.json @@ -184,6 +184,24 @@ } } }, + { + "name": "shape/a-path-of-no-break-and-ideographic-spaces", + "route": "llm.chat", + "body": { + "prompt": "Read the page.", + "attachments": [ + "\u00a0\u3000" + ] + }, + "expect": { + "error": { + "status": 400, + "message_contains": [ + "attachments[0].path must be a path inside llm.attachments.root" + ] + } + } + }, { "name": "shape/pages-that-are-not-pages", "route": "llm.chat", @@ -590,6 +608,69 @@ } } }, + { + "name": "root/a-path-of-a-byte-order-mark-is-a-name", + "route": "llm.chat", + "body": { + "prompt": "Read the page.", + "attachments": [ + "\ufeff" + ] + }, + "files": { + "page.png": "pixel.png" + }, + "expect": { + "error": { + "status": 400, + "message_contains": [ + "attachments[0]: not found" + ] + } + } + }, + { + "name": "root/a-path-of-a-separator-character-is-a-name", + "route": "llm.chat", + "body": { + "prompt": "Read the page.", + "attachments": [ + "\u001c" + ] + }, + "files": { + "page.png": "pixel.png" + }, + "expect": { + "error": { + "status": 400, + "message_contains": [ + "attachments[0]: not found" + ] + } + } + }, + { + "name": "root/a-path-of-a-next-line-character-is-a-name", + "route": "llm.chat", + "body": { + "prompt": "Read the page.", + "attachments": [ + "\u0085" + ] + }, + "files": { + "page.png": "pixel.png" + }, + "expect": { + "error": { + "status": 400, + "message_contains": [ + "attachments[0]: not found" + ] + } + } + }, { "name": "root/a-folder", "route": "llm.chat", diff --git a/tests/vectors/llm-helper-vectors.json b/tests/vectors/llm-helper-vectors.json index a29f1e9..2197d94 100644 --- a/tests/vectors/llm-helper-vectors.json +++ b/tests/vectors/llm-helper-vectors.json @@ -1,7 +1,7 @@ { "contract": "llm-helper", "version": 1, - "description": "One contract, two function hosts. mercury-python and mercury-nodejs ship this file byte-identical and run every case against their own fake of the Anthropic SDK, so the two helpers cannot drift apart. A case's config may name llm.backend, and the harness then installs its fake under that backend's shape (bedrock: no server-side fallbacks, the messages namespace, and the model id by surface - llm.aws.api mantle, the default, prefixes a bare id with anthropic.; runtime sends every id as written). A case names the route, the config keys in force, the request body and what the fake provider does; the expectation is the exact SDK call (namespace, parameters, options), then either the reply map or the error (status and message fragments) for llm.chat, or the head, the segments in order, the terminal metadata (a subset) or the in-band error for llm.stream. numbers states how a number is read, the same in both packs: its own description gives the rule and what the harness checks.", + "description": "One contract, two function hosts. mercury-python and mercury-nodejs ship this file byte-identical and run every case against their own fake of the Anthropic SDK, so the two helpers cannot drift apart. A case's config may name llm.backend, and the harness then installs its fake under that backend's shape (bedrock: no server-side fallbacks, the messages namespace, and the model id by surface - llm.aws.api mantle, the default, prefixes a bare id with anthropic.; runtime sends every id as written). A case names the route, the config keys in force, the request body and what the fake provider does; the expectation is the exact SDK call (namespace, parameters, options), then either the reply map or the error (status and message fragments) for llm.chat, or the head, the segments in order, the terminal metadata (a subset) or the in-band error for llm.stream. numbers states how a number is read, switches how a switch of the configuration is read and start which settings stop the application when it starts, each the same in both packs: a section's own description gives the rule and what the harness checks.", "provider_kinds": { "message": "succeeds: deltas are the token batches; text is the final message text (default: the deltas joined); usage, model, stop_reason, request_id (the request-id response header), stop_details", "status": "an HTTP error from the API: status, type, message, request_id; after = the number of deltas delivered before it is raised (0: at open), deltas = those batches", @@ -11,7 +11,7 @@ "hang": "never answers - the helper's own deadline must fire" }, "numbers": { - "description": "How a number is read, the same in both packs: one list of values, each read as a whole number, as a duration and as the pages of a PDF. whole is the whole number the value spells, duration the seconds it spells, pages the ranges [first, last] it names, in the order named; null where it spells none, and \"absent\" for a null, which is a field left out. The rule: a whole number is a JSON number with a whole value (16000, or 16000.0, which one runtime cannot tell from it) or a string of the ASCII digits 0 to 9, up to 9007199254740991, the largest whole number both runtimes hold exactly; a duration is such a number of seconds, or ASCII digits and one of s, m, h, d, up to that many seconds; pages are numbers from 1 and ranges of them, joined by commas. The white space both runtimes' own trim takes (tab to carriage return, space, no-break space and the other space separators, the line and paragraph separators) is ignored around a whole number and a duration and anywhere in pages; any other character spells nothing - a sign, an underscore, a point, a digit of another script, a byte order mark. The harness reads each value as params.max_tokens (minimum 1) of llm.chat and, when it is a string, as the setting llm.max.retries (minimum 0): the SDK call carries the number, or the request is refused before any provider call. It reads it as the ttl (minimum 1) and as the retention (minimum 0) of a first loop turn on the memory store: the stored record lives that many seconds, or carries that retention, or the turn is refused before any provider call and no record is stored. It reads it as attachments[0].pages through the request check, which decides the shape before any file is read. A field refuses a number below its minimum as it refuses a value that spells none: status 400 and the text of refusals for its kind, {name} being the field and {minimum} its minimum.", + "description": "How a number is read, the same in both packs: one list of values, each read as a whole number, as a duration and as the pages of a PDF. whole is the whole number the value spells, duration the seconds it spells, pages the ranges [first, last] it names, in the order named; null where it spells none, and \"absent\" for a null, which is a field left out. The rule: a whole number is a JSON number with a whole value (16000, or 16000.0, which one runtime cannot tell from it) or a string of the ASCII digits 0 to 9, up to 9007199254740991, the largest whole number both runtimes hold exactly; a duration is such a number of seconds, or ASCII digits and one of s, m, h, d, up to that many seconds; pages are numbers from 1 and ranges of them, joined by commas. The white space both runtimes' own trim takes (tab to carriage return, space, no-break space and the other space separators, the line and paragraph separators) is ignored around a number - around a whole number and a duration, and in pages around each page number, so around a comma and a hyphen - and never inside one; any other character spells nothing - a sign, an underscore, a point, a digit of another script, a byte order mark. The harness reads each value as params.max_tokens (minimum 1) of llm.chat and, when it is a string, as the setting llm.max.retries (minimum 0): the SDK call carries the number, or the request is refused before any provider call. It reads it as the ttl (minimum 1) and as the retention (minimum 0) of a first loop turn on the memory store: the stored record lives that many seconds, or carries that retention, or the turn is refused before any provider call and no record is stored. It reads it as attachments[0].pages through the request check, which decides the shape before any file is read. A field refuses a number below its minimum as it refuses a value that spells none: status 400 and the text of refusals for its kind, {name} being the field and {minimum} its minimum.", "refusals": { "whole": "{name} must be a whole number >= {minimum}", "duration": "{name} must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= {minimum}", @@ -138,12 +138,7 @@ "value": "5 12", "whole": null, "duration": null, - "pages": [ - [ - 512, - 512 - ] - ] + "pages": null }, { "name": "a-byte-order-mark-before", @@ -757,6 +752,32 @@ ] ] }, + { + "name": "two-pages-without-a-comma", + "value": "1 3", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-space-inside-a-page-of-a-range", + "value": "1 0-12", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "line-breaks-around-a-hyphen", + "value": "1\n-\n3", + "whole": null, + "duration": null, + "pages": [ + [ + 1, + 3 + ] + ] + }, { "name": "pages-with-a-byte-order-mark", "value": "1\ufeff-3", @@ -827,6 +848,553 @@ } ] }, + "switches": { + "description": "How a switch of the configuration is read, the same in both packs: true or false, the boolean or the text in any letter case; no value and an empty one are the switch's default; any other value - yes, on, 1, a number, text with a space around it - is refused by name, where it used to be read as off without a word. on is what the value reads as: true, false, \"default\", or null for a value that is refused. The harness gives each value to llm.transcript.audit.postgres.ssl (default true) and to llm.transcript.redis.ssl (default false) and builds the store from the connection keys: the connection is made with TLS or without it, or the build is refused with status 500 and the text of refusal, {name} being the key. A value reaches the reader as a boolean or as text, whichever the configuration gave; the two read the same.", + "refusal": "{name} must be true or false", + "probes": [ + { + "name": "the-boolean-true", + "value": true, + "on": true + }, + { + "name": "the-boolean-false", + "value": false, + "on": false + }, + { + "name": "true", + "value": "true", + "on": true + }, + { + "name": "false", + "value": "false", + "on": false + }, + { + "name": "upper-case-true", + "value": "TRUE", + "on": true + }, + { + "name": "capitalized-true", + "value": "True", + "on": true + }, + { + "name": "upper-case-false", + "value": "FALSE", + "on": false + }, + { + "name": "mixed-case-false", + "value": "fAlSe", + "on": false + }, + { + "name": "empty-text", + "value": "", + "on": "default" + }, + { + "name": "no-value", + "value": null, + "on": "default" + }, + { + "name": "yes", + "value": "yes", + "on": null + }, + { + "name": "no", + "value": "no", + "on": null + }, + { + "name": "on", + "value": "on", + "on": null + }, + { + "name": "off", + "value": "off", + "on": null + }, + { + "name": "one-as-text", + "value": "1", + "on": null + }, + { + "name": "zero-as-text", + "value": "0", + "on": null + }, + { + "name": "a-word", + "value": "maybe", + "on": null + }, + { + "name": "a-letter", + "value": "t", + "on": null + }, + { + "name": "spaces-around-true", + "value": " true ", + "on": null + }, + { + "name": "the-number-one", + "value": 1, + "on": null + }, + { + "name": "the-number-zero", + "value": 0, + "on": null + }, + { + "name": "a-list", + "value": [ + true + ], + "on": null + } + ] + }, + "start": { + "description": "What stops the application when it starts, the same in both packs: a setting that is wrong is a deployment error, refused by name before a request finds it, where it used to be refused on the first request that needed it - some after the model was called - or read as off. A case names the start-up step (settings: the settings a request falls back on and the transcript store with its connection keys; attachments: the limits and the root; audit: the audit store), the configuration keys in force and refused: null when the step passes, else the refusal. A step that refuses logs one line at ERROR, the text of voices for the step with {message} the refusal, and stops the start; a step that passes logs none. The harness builds the stores from the connection keys with clients that reach no server, so a step that passes opens nothing. A request's own params are not settings: they keep their 400 on the request. A timer takes at most 2147483647 ms (about 24.8 days, the longest wait both runtimes' timers hold), a port is at most 65535, and the audit retention at most 1000000d, with which a conversation's expires_at is a date of a four-digit year.", + "voices": { + "settings": "llm.helper cannot start - {message}", + "attachments": "attachments cannot start - {message}", + "audit": "transcript audit store cannot start - {message}" + }, + "cases": [ + { + "name": "settings/the-defaults-start", + "boot": "settings", + "config": {}, + "refused": null + }, + { + "name": "settings/an-unknown-provider", + "boot": "settings", + "config": { + "llm.provider": "gemini" + }, + "refused": "unknown LLM provider 'gemini' - this helper serves: anthropic" + }, + { + "name": "settings/an-unknown-backend", + "boot": "settings", + "config": { + "llm.backend": "vertex" + }, + "refused": "unknown LLM backend 'vertex' - this helper serves: anthropic, bedrock" + }, + { + "name": "settings/an-unknown-bedrock-surface", + "boot": "settings", + "config": { + "llm.backend": "bedrock", + "llm.aws.api": "console" + }, + "refused": "llm.aws.api must be one of: mantle, runtime" + }, + { + "name": "settings/the-bedrock-surface-is-read-for-bedrock-only", + "boot": "settings", + "config": { + "llm.aws.api": "console" + }, + "refused": null + }, + { + "name": "settings/max-tokens-not-a-number", + "boot": "settings", + "config": { + "llm.max.tokens": "lots" + }, + "refused": "llm.max.tokens must be a whole number >= 1" + }, + { + "name": "settings/max-tokens-zero", + "boot": "settings", + "config": { + "llm.max.tokens": "0" + }, + "refused": "llm.max.tokens must be a whole number >= 1" + }, + { + "name": "settings/max-tokens-in-the-digits-of-another-script", + "boot": "settings", + "config": { + "llm.max.tokens": "\u0663" + }, + "refused": "llm.max.tokens must be a whole number >= 1" + }, + { + "name": "settings/timeout-not-a-number", + "boot": "settings", + "config": { + "llm.timeout.ms": "soon" + }, + "refused": "llm.timeout.ms must be a whole number >= 1" + }, + { + "name": "settings/timeout-above-the-longest-timer", + "boot": "settings", + "config": { + "llm.timeout.ms": "2147483648" + }, + "refused": "llm.timeout.ms must be a whole number >= 1" + }, + { + "name": "settings/the-longest-timer-starts", + "boot": "settings", + "config": { + "llm.timeout.ms": "2147483647" + }, + "refused": null + }, + { + "name": "settings/retries-not-a-number", + "boot": "settings", + "config": { + "llm.max.retries": "two" + }, + "refused": "llm.max.retries must be a whole number >= 0" + }, + { + "name": "settings/an-unknown-effort", + "boot": "settings", + "config": { + "llm.effort": "extreme" + }, + "refused": "llm.effort must be one of: low, medium, high, xhigh, max" + }, + { + "name": "settings/fallbacks-neither-default-nor-off", + "boot": "settings", + "config": { + "llm.fallbacks": "maybe" + }, + "refused": "llm.fallbacks must be 'default' or 'off'" + }, + { + "name": "settings/batch-logging-not-a-switch", + "boot": "settings", + "config": { + "llm.log.batches": "yes" + }, + "refused": "llm.log.batches must be true or false" + }, + { + "name": "settings/ttl-not-a-duration", + "boot": "settings", + "config": { + "llm.transcript.ttl": "week" + }, + "refused": "llm.transcript.ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 1" + }, + { + "name": "settings/ttl-zero", + "boot": "settings", + "config": { + "llm.transcript.ttl": "0" + }, + "refused": "llm.transcript.ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 1" + }, + { + "name": "settings/retention-not-a-duration", + "boot": "settings", + "config": { + "llm.transcript.retention": "forever" + }, + "refused": "llm.transcript.retention must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 0" + }, + { + "name": "settings/an-unknown-transcript-store", + "boot": "settings", + "config": { + "llm.transcript.store": "rediss" + }, + "refused": "llm.transcript.store must be one of: memory, redis" + }, + { + "name": "settings/redis-port-not-a-number", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.port": "sixty" + }, + "refused": "llm.transcript.redis.port must be a whole number >= 1" + }, + { + "name": "settings/redis-port-above-the-highest", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.port": "65536" + }, + "refused": "llm.transcript.redis.port must be a whole number >= 1" + }, + { + "name": "settings/redis-database-not-a-number", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.database": "x" + }, + "refused": "llm.transcript.redis.database must be a whole number >= 0" + }, + { + "name": "settings/redis-timeout-not-a-number", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.timeout.ms": "x" + }, + "refused": "llm.transcript.redis.timeout.ms must be a whole number >= 1" + }, + { + "name": "settings/redis-timeout-above-the-longest-timer", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.timeout.ms": "2147483648" + }, + "refused": "llm.transcript.redis.timeout.ms must be a whole number >= 1" + }, + { + "name": "settings/redis-tls-not-a-switch", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.ssl": "yes" + }, + "refused": "llm.transcript.redis.ssl must be true or false" + }, + { + "name": "settings/the-redis-keys-are-read-for-redis-only", + "boot": "settings", + "config": { + "llm.transcript.store": "memory", + "llm.transcript.redis.port": "sixty" + }, + "refused": null + }, + { + "name": "settings/every-setting-well-formed-starts", + "boot": "settings", + "config": { + "llm.provider": "anthropic", + "llm.backend": "bedrock", + "llm.aws.api": "runtime", + "llm.max.tokens": "2048", + "llm.timeout.ms": "9000", + "llm.max.retries": "0", + "llm.effort": "LOW", + "llm.fallbacks": "OFF", + "llm.log.batches": "TRUE", + "llm.transcript.ttl": "12h", + "llm.transcript.retention": "0", + "llm.transcript.store": "redis", + "llm.transcript.redis.port": "65535", + "llm.transcript.redis.database": "2", + "llm.transcript.redis.timeout.ms": "2147483647", + "llm.transcript.redis.ssl": "true" + }, + "refused": null + }, + { + "name": "attachments/the-defaults-start", + "boot": "attachments", + "config": {}, + "refused": null + }, + { + "name": "attachments/max-count-not-a-number", + "boot": "attachments", + "config": { + "llm.attachments.max.count": "many" + }, + "refused": "llm.attachments.max.count must be a whole number >= 1" + }, + { + "name": "attachments/max-bytes-not-a-number", + "boot": "attachments", + "config": { + "llm.attachments.max.bytes": "big" + }, + "refused": "llm.attachments.max.bytes must be a whole number >= 1" + }, + { + "name": "attachments/max-bytes-zero", + "boot": "attachments", + "config": { + "llm.attachments.max.bytes": "0" + }, + "refused": "llm.attachments.max.bytes must be a whole number >= 1" + }, + { + "name": "attachments/limits-well-formed-start", + "boot": "attachments", + "config": { + "llm.attachments.max.count": "5", + "llm.attachments.max.bytes": "1000" + }, + "refused": null + }, + { + "name": "audit/grace-not-a-duration", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.grace": "x" + }, + "refused": "llm.transcript.audit.grace must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 1" + }, + { + "name": "audit/retention-not-a-duration", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.retention": "forever" + }, + "refused": "llm.transcript.audit.retention must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 0" + }, + { + "name": "audit/retention-above-the-longest", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.retention": "1000001d" + }, + "refused": "llm.transcript.audit.retention must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 0" + }, + { + "name": "audit/the-longest-retention-starts", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.retention": "1000000d", + "llm.transcript.audit.sweep.ms": "0" + }, + "refused": null + }, + { + "name": "audit/sweep-not-a-number", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.sweep.ms": "soon" + }, + "refused": "llm.transcript.audit.sweep.ms must be a whole number >= 0" + }, + { + "name": "audit/sweep-above-the-longest-timer", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.sweep.ms": "2147483648" + }, + "refused": "llm.transcript.audit.sweep.ms must be a whole number >= 0" + }, + { + "name": "audit/single-calls-not-a-switch", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.store": "memory", + "llm.transcript.audit.single": "yes" + }, + "refused": "llm.transcript.audit.single must be true or false" + }, + { + "name": "audit/single-calls-without-the-working-store", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.single": "true" + }, + "refused": "llm.transcript.audit.single needs the working store - set llm.transcript.store (redis, or memory for a single process)" + }, + { + "name": "audit/postgres-tls-not-a-switch", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.postgres.ssl": "yes" + }, + "refused": "llm.transcript.audit.postgres.ssl must be true or false" + }, + { + "name": "audit/postgres-port-not-a-number", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.postgres.port": "x" + }, + "refused": "llm.transcript.audit.postgres.port must be a whole number >= 1" + }, + { + "name": "audit/postgres-port-above-the-highest", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.postgres.port": "65536" + }, + "refused": "llm.transcript.audit.postgres.port must be a whole number >= 1" + }, + { + "name": "audit/postgres-timeout-above-the-longest-timer", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.postgres.timeout.ms": "2147483648" + }, + "refused": "llm.transcript.audit.postgres.timeout.ms must be a whole number >= 1" + }, + { + "name": "audit/an-unknown-audit-store", + "boot": "audit", + "config": { + "llm.transcript.audit": "mongo" + }, + "refused": "llm.transcript.audit must be one of: postgres" + }, + { + "name": "audit/every-setting-well-formed-starts", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.store": "memory", + "llm.transcript.audit.grace": "2h", + "llm.transcript.audit.retention": "30d", + "llm.transcript.audit.sweep.ms": "0", + "llm.transcript.audit.single": "TRUE", + "llm.transcript.audit.postgres.ssl": "False", + "llm.transcript.audit.postgres.port": "5433", + "llm.transcript.audit.postgres.timeout.ms": "2500" + }, + "refused": null + }, + { + "name": "audit/the-audit-keys-are-read-with-an-audit-store-only", + "boot": "audit", + "config": { + "llm.transcript.audit.grace": "x", + "llm.transcript.audit.sweep.ms": "soon" + }, + "refused": null + } + ] + }, "cases": [ { "name": "prep/missing-prompt-and-messages", @@ -1047,6 +1615,24 @@ } } }, + { + "name": "prep/timeout-above-the-longest-timer", + "route": "llm.chat", + "body": { + "prompt": "x", + "params": { + "timeout_ms": 2147483648 + } + }, + "expect": { + "error": { + "status": 400, + "message_contains": [ + "params.timeout_ms must be a whole number >= 1" + ] + } + } + }, { "name": "prep/bad-effort", "route": "llm.chat", @@ -1737,6 +2323,62 @@ } } }, + { + "name": "chat/the-longest-timeout-is-accepted", + "route": "llm.chat", + "body": { + "prompt": "x", + "params": { + "timeout_ms": 2147483647 + } + }, + "provider": { + "kind": "message", + "model": "claude-opus-5-5", + "stop_reason": "end_turn", + "deltas": [ + "ok" + ], + "usage": { + "input_tokens": 5, + "output_tokens": 1 + }, + "request_id": "req_ok_001" + }, + "expect": { + "sdk": { + "namespace": "beta.messages", + "params": { + "model": "claude-opus-5-5", + "max_tokens": 16000, + "messages": [ + { + "role": "user", + "content": "x" + } + ], + "betas": [ + "server-side-fallback-2026-07-01" + ], + "fallbacks": "default" + }, + "options": { + "timeout_ms": 2147483647, + "max_retries": 2 + } + }, + "result": { + "text": "ok", + "model": "claude-opus-5-5", + "stop_reason": "end_turn", + "usage": { + "input_tokens": 5, + "output_tokens": 1 + }, + "request_id": "req_ok_001" + } + } + }, { "name": "chat/other-model-gets-no-fallbacks", "route": "llm.chat", From 39cc790559fb469a57366ab3b1a2220279270dc8 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:02 -0800 Subject: [PATCH 4/5] fix(ask-person, agent-question): one reader of a time, a number, a duration and a switch; a signed payload has one spelling A time is a date, T, a time to the minute or the second, and Z or an offset, read to the millisecond by one rule in both packs. A wait whose expiry is past the year 9999 is a 400. turn, ttl, the list's since, before and limit and every setting follow the number and duration rule; a switch that is neither true nor false stops the boot. The bytes under a ticket's signature are the canonical JSON of its five fields. A setting that sets a timer is at most 2147483647 ms, a port at most 65535, a turn at most 2147483647. A required text is blank by the same 24 characters in both packs. Co-Authored-By: Claude Fable 5.2 --- extensions/agent-question/README.md | 44 +- extensions/agent-question/agent_question.py | 302 +- extensions/ask-person/README.md | 65 +- extensions/ask-person/ask_person.py | 350 +- tests/test_agent_question.py | 395 +- tests/test_ask_person.py | 460 +- tests/vectors/agent-question-vectors.json | 6227 ++++++++- tests/vectors/ask-person-vectors.json | 12978 +++++++++++++++--- 8 files changed, 17914 insertions(+), 2907 deletions(-) diff --git a/extensions/agent-question/README.md b/extensions/agent-question/README.md index eb31219..88adf2b 100644 --- a/extensions/agent-question/README.md +++ b/extensions/agent-question/README.md @@ -10,7 +10,12 @@ application is one of those routes. It is a standalone application on the packag - **Intake.** `agent.question.inbox` is a composable function reached over Event-over-HTTP like any peer function. It writes nothing - the record is the recorder's (`question.audit` in the ask-person process) - it checks the event and - wakes the feed, so a connected device sees the row the moment it is recorded. + wakes the feed, so a connected device sees the row the moment it is recorded. The event's `turn` is read as the main + flow reads it - a whole number: a JSON number with a whole value or ASCII digits, at most 2147483647, the largest the + record's `turn` column holds - and the answer carries the number. Its `requested_at` and a wait's `expires_at` are + times by the main flow's one reader - a date, an upper-case `T`, a time, then `Z` or an offset `+HH:MM` - and a text + the event must carry is blank by the main flow's rule, the white space of a number and no other character; anything + else is a 400. - **The person's side** is `resources/rest.yaml` - the engines' REST automation (RFC-0018), served by the pack's host in front of this process's private functions, with `rest.automation: true` in `application.yml`: `GET /questions/config` (`question.config`) tells the UI how to sign in (the auth mode, the title and, under `oauth2`, the issuer, the public @@ -31,10 +36,19 @@ application is one of those routes. It is a standalone application on the packag `via` from the request's session map. An error is the engines' standard body, `{"status", "message", "type": "error"}`. A row id and a stream's cursor - `Last-Event-ID`, else `since`, else the beginning - are one to nineteen ASCII digits from start to end, no larger than the record's `BIGINT` columns hold (9223372036854775807); anything else is a 400. + `GET /questions` reads its `since` and its `before` the same way (an empty `before` is the newest page), and a + `limit` - there and in `GET /transcripts` - is a whole number: ASCII digits, at most 9007199254740991, with white + space ignored around it, held between 1 and the most a page takes (1000 rows, 200 conversations); anything else is a + 400. A row is told by the numbers it has: a page, a stream's event and a refusal carry `id` and `seq` with every + digit, past 9007199254740991 too, and so is a whole number that large in a row's calls or in a decision the click + forwards. The `before` of `GET /transcripts` is a time by the main flow's one reader - `2026-11-19T11:00:00Z`, or + the same instant at an offset, whose plus sign is `%2B` in a URL - and the store is asked by that instant in UTC, to + the millisecond; anything else is a 400. - **The feed** reads the record's change sequence: a poll every `question.poll` (1 s) and a wake-up from the intake or a click, whichever comes first. A wait is `open` until the engine accepts the decision (`answered`) or finds nothing waiting (`expired`); an advice has no state - whether a person has read it is the device's, kept by the UI. The - record is never written here; the recorder's sweeper expires waits and the installation's purge retires rows. + record is never written here; the recorder's sweeper expires waits and the installation's purge retires rows. The + health reply tells the feed's cursor: a number up to 9007199254740991 and its digits, as text, beyond. This app is the backend in both packs. Its front-end - the React UI with the question-and-answer panel, the history with infinite scroll and the transcript browser - is built and maintained in the Node.js pack only, so there is one app to @@ -105,11 +119,25 @@ flow as `decided_by` under its own bearer (`question.reply.token`, the reply end | `question.reply.timeout` | `10s` | how long the reply endpoint may take | | `question.page.title` | `Agent questions` | the UI's title, told through `GET /questions/config` | +A setting is read by the main flow's rule, whether a YAML file holds the value or a `${NAME:default}` reference or a +`-D` override gives it as text: `.port` and `.timeout.ms` are whole numbers - ASCII digits, a port 1 to 65535; +`question.poll` and `question.reply.timeout` are durations - seconds, or `ms`, `s`, `m`, `h`, `d` right after the +number - more than zero. A setting that sets a timer - the two durations and `.timeout.ms` - takes at most 2147483647 +ms (about 24.8 days), the longest delay both runtimes' timers hold; the host's `event.stream.keep.alive` is also how +often a quiet stream looks for its device, so one longer than that stops the boot too, by the host's own message. +`question.store.postgres.ssl` is a switch: `true` or `false`, the boolean or the text in any letter case; no value and +an empty one are the default; any other value stops the boot by the key's name instead of being read as on. So does a +number or a duration that is not one. A setting's text loses the white space of the number rule around it and no other +character. + ## Tests -`tests/test_agent_question.py` runs the shared vectors (`tests/vectors/agent-question-vectors.json`: the event the intake -accepts or refuses, the request the click sends, the pages the replay and the history read, the row id and the cursor a -request names) and drives the app in-process as the reader of the record: the intake waking the feed, the replay and the -history pages and the stream, the transcripts browsed, a decision forwarded to a fake reply endpoint and the row re-read -as the recorder left it, the two auth modes with the UI's configuration, the PostgreSQL reader's statements on a -recording fake of the pool, and - gated on `AGENT_QUESTION_TEST_URL` - the schemas and the rows on a live PostgreSQL. +`tests/test_agent_question.py` runs the shared vectors (`tests/vectors/agent-question-vectors.json`: the event the +intake accepts or refuses, the request the click sends, the pages the replay and the history read, the row id and the +cursor a request names, what `GET /questions` asks for, a page size, rows past the whole numbers a double holds, a +number, a duration and a switch as the one rule reads them, a time as the one reader reads it and the white space +around a text) and drives the app in-process as the reader of the record: +the intake waking the feed, the replay and the history pages and the stream, the transcripts browsed, a decision +forwarded to a fake reply endpoint and the row re-read as the recorder left it, the two auth modes with the UI's +configuration, the PostgreSQL reader's statements on a recording fake of the pool, and - gated on +`AGENT_QUESTION_TEST_URL` - the schemas and the rows on a live PostgreSQL. diff --git a/extensions/agent-question/agent_question.py b/extensions/agent-question/agent_question.py index 7faa3de..520b061 100644 --- a/extensions/agent-question/agent_question.py +++ b/extensions/agent-question/agent_question.py @@ -47,7 +47,7 @@ import sys from collections.abc import Mapping, Sequence from dataclasses import dataclass -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Any, Protocol import aiohttp @@ -66,7 +66,6 @@ EventStreamWriter, app_config, get_logger, - iso_utc, platform, preload, ) @@ -135,8 +134,37 @@ MISSING_POSTGRES = "question.store is postgres but psycopg is not installed - pip install 'mercury-composable[postgres]'" # what the UI is told when the record's store cannot be read: a 503 by type, never the store's own message _RECORD_UNAVAILABLE = "the question record is not available" -DURATION = re.compile(r"^(\d+)\s*(ms|s|m|h|d)?$") +# how a number is read, the same in both packs and in every extension: the largest whole number both packs hold +# exactly (2**53 - 1) - above it the Node.js twin's numbers round, and the twins would read two different numbers +MAX_WHOLE = 9007199254740991 +# the longest wait both packs' timers hold, in milliseconds (2**31 - 1, about 24.8 days): the Node.js twin's timers +# keep a delay in 32 bits with a sign and fire at once on a longer one, so a setting that sets a timer takes no more, +# here as there +MAX_TIMER_MS = 2147483647 +# the highest port a connection can name +MAX_PORT = 65535 +# the largest turn the question record holds: its turn column is a 32-bit INTEGER (extensions/ask-person/schema) +MAX_TURN = 2147483647 +# the white space ignored around a number and a duration: the characters Python's str.strip() and JavaScript's +# trim() both take for white space, so neither pack accepts a character the other refuses +_SPACE = r"[\t-\r \xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]" +# the same 24 characters as a text, to take off the ends of a text: a required text is blank and a setting's text is +# trimmed by these and no other. Each runtime's own trim takes a few more - this one's U+001C to U+001F and U+0085, +# the Node.js twin's U+FEFF - which here are characters of a name +_SPACES = "\t\n\x0b\x0c\r \xa0\u1680" + "".join(map(chr, range(0x2000, 0x200B))) + "\u2028\u2029\u202f\u205f\u3000" +# the digits 0 to 9 and no other, by flag: Python's own \d takes the digits of every script +WHOLE = re.compile(rf"^{_SPACE}*(\d+){_SPACE}*$", re.ASCII) +DURATION = re.compile(rf"^{_SPACE}*(\d+)(ms|s|m|h|d)?{_SPACE}*$", re.ASCII) UNIT_MS = {"ms": 1, "s": 1000, "m": 60_000, "h": 3_600_000, "d": 86_400_000} +# a time as both packs read one: a date, an upper-case T, a time to the minute or to the second - the second with a +# fraction of one to nine digits at most - and Z or an offset in hours and minutes +ISO_TIME = re.compile( + r"(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(?:\.(\d{1,9}))?)?(?:Z|([+-])(\d\d):(\d\d))", re.ASCII +) +# the host's key of the keep-alive interval of a Server-Sent Events reply, which is also how often a quiet stream of +# this app looks for its device, and what the host says of a value it refuses +KEEP_ALIVE = "event.stream.keep.alive" +_KEEP_ALIVE_RULE = f"{KEEP_ALIVE} must be a duration such as 30s, 2m or 500ms (seconds, ms, s, m, h, d), or 0 for none" class QuestionError(Exception): @@ -152,30 +180,100 @@ def __init__(self, status: int, message: str) -> None: self.message = message -def duration_ms(value: Any) -> int | None: - if isinstance(value, bool): +def _number_text(value: Any) -> str | None: + """What a number is read from: a string as written, or the digits of a JSON number with a whole value - an + integer, or a float, which the Node.js twin cannot tell from one. None for anything else: a boolean, a + fraction, a number beyond MAX_WHOLE.""" + if isinstance(value, str): + return value + if isinstance(value, float) and value.is_integer(): + value = int(value) + if isinstance(value, bool) or not isinstance(value, int) or abs(value) > MAX_WHOLE: return None - if isinstance(value, int): - return value * 1000 if value >= 0 else None - if not isinstance(value, str): + return str(value) + + +def _digits(digits: str) -> int | None: + """The whole number a run of ASCII digits spells, or None above MAX_WHOLE - told by the count of its digits + first, so a run of any length is judged without being converted.""" + significant = digits.lstrip("0") + if len(significant) > len(str(MAX_WHOLE)): return None - match = DURATION.fullmatch(value.strip()) - if not match: + number = int(significant or "0") + return number if number <= MAX_WHOLE else None + + +def whole_number(value: Any) -> int | None: + """The whole number a value spells - a JSON number with a whole value, or ASCII digits with white space + around them at most - up to MAX_WHOLE; None when it spells none: a sign, an underscore, a point or an + exponent in text, a digit of another script.""" + text = _number_text(value) + match = WHOLE.fullmatch(text) if text is not None else None + return _digits(match.group(1)) if match else None + + +def duration_ms(value: Any) -> int | None: + """Milliseconds from a whole number of seconds or a duration such as 500ms, 30m, 12h or 2d - such a number + and, right after it, one of ms, s, m, h, d - up to MAX_WHOLE milliseconds; None when the value is neither.""" + text = _number_text(value) + match = DURATION.fullmatch(text) if text is not None else None + count = _digits(match.group(1)) if match else None + if match is None or count is None: return None - return int(match.group(1)) * UNIT_MS[match.group(2) or "s"] + ms = count * UNIT_MS[match.group(2) or "s"] + return ms if ms <= MAX_WHOLE else None + + +def switch_value(value: Any, default: bool) -> bool | None: + """What a switch is set to: the boolean, or the text true or false in any letter case; no value and an empty + one are the default. None for any other value - it is never read as off.""" + if value is None or value == "": + return default + if isinstance(value, bool): + return value + lowered = value.lower() if isinstance(value, str) else "" + return lowered == "true" if lowered in ("true", "false") else None + + +def _trimmed(text: str) -> str: + """A text without the white space around it - the 24 characters of the number rule, the same in both packs, + where str.strip() alone takes a few more. A blank text leaves nothing.""" + return text.strip(_SPACES) def parse_iso(text: str) -> datetime | None: - candidate = text.strip() - if candidate.endswith(("Z", "z")): - candidate = candidate[:-1] + "+00:00" + """An ISO-8601 time with an offset or ``Z``, as a UTC datetime; None when it is not one. One reader in both + packs and in the main flow: a date ``YYYY-MM-DD``, an upper-case ``T``, a time ``HH:MM`` or ``HH:MM:SS`` - the + second with a fraction of one to nine digits at most - then ``Z`` or ``+HH:MM`` / ``-HH:MM``, and nothing + before or after it; a date the calendar has, in the years 0001 to 9999 as written and in UTC. The instant is + read to the millisecond: a longer fraction is cut, never rounded.""" + match = ISO_TIME.fullmatch(text) + if match is None: + return None + year, month, day, hour, minute = (int(part) for part in match.group(1, 2, 3, 4, 5)) + second, fraction, sign = match.group(6, 7, 8) + offset_hours, offset_minutes = (int(part or 0) for part in match.group(9, 10)) + if offset_hours > 23 or offset_minutes > 59: + return None + offset = timedelta(hours=offset_hours, minutes=offset_minutes) + millisecond = int((fraction or "").ljust(3, "0")[:3]) try: - value = datetime.fromisoformat(candidate) - except ValueError: + # datetime refuses a date the calendar does not have and a time the clock does not + written = datetime(year, month, day, hour, minute, int(second or 0), millisecond * 1000, tzinfo=UTC) + return written + offset if sign == "-" else written - offset + # a ValueError is the date or the time; an OverflowError the instant, outside the years in UTC + except (ValueError, OverflowError): return None - if value.tzinfo is None: - value = value.replace(tzinfo=UTC) - return value.astimezone(UTC) + + +def _utc_stamp(moment: datetime) -> str: + """The text both packs write for an instant: UTC, to the millisecond, the year in four digits - spelled out + here, since strftime leaves a year before 1000 unpadded on some platforms.""" + utc = (moment if moment.tzinfo is not None else moment.replace(tzinfo=UTC)).astimezone(UTC) + return ( + f"{utc.year:04d}-{utc.month:02d}-{utc.day:02d}T{utc.hour:02d}:{utc.minute:02d}:{utc.second:02d}" + f".{utc.microsecond // 1000:03d}Z" + ) # --- configuration ---------------------------------------------------------------------------- @@ -200,24 +298,45 @@ class Settings: def _text(config: AppConfig, key: str, default: str = "") -> str: value = config.get(key) - return default if value is None else str(value).strip() + return default if value is None else _trimmed(str(value)) def _timeout(config: AppConfig, key: str, default: str) -> int: + """A setting that sets a timer: a duration of more than nothing and of no more than a timer holds in both + packs.""" value = config.get(key) ms = duration_ms(default if value is None else value) - if ms is None or ms <= 0: + if ms is None or ms <= 0 or ms > MAX_TIMER_MS: raise QuestionError(f"{key} must be a duration such as 10s or 2m (seconds, s, m, h, d) > 0") return ms def _whole_ms(config: AppConfig, key: str, default: int) -> int: - """A key named in milliseconds (``timeout.ms``): a whole number > 0.""" + """A key named in milliseconds (``timeout.ms``): a whole number > 0, and no more than a timer holds.""" value = config.get(key) - text = str(default if value is None else value).strip() - if not text.isdigit() or int(text) <= 0: + number = whole_number(default if value is None else value) + if number is None or number <= 0 or number > MAX_TIMER_MS: raise QuestionError(f"{key} must be a whole number of milliseconds > 0") - return int(text) + return number + + +def _check_keep_alive(config: AppConfig) -> None: + """The host's keep-alive interval sets a timer of this app too - a quiet stream looks for its device that + often: one longer than a timer holds stops the boot by the key's own message. A value that is no duration is + the host's to refuse.""" + value = config.get(KEEP_ALIVE) + ms = duration_ms("30s" if value is None else value) + if ms is not None and ms > MAX_TIMER_MS: + raise QuestionError(_KEEP_ALIVE_RULE) + + +def _switch(config: AppConfig, key: str, default: bool) -> bool: + """A switch of the configuration, or a QuestionError naming the key: a value that is neither true nor false + stops the boot instead of leaving the switch off.""" + switch = switch_value(config.get(key), default) + if switch is None: + raise QuestionError(f"{key} must be true or false") + return switch def _check_oauth2(issuer: str, jwks_url: str, client_id: str) -> None: @@ -245,16 +364,19 @@ def load_settings(config: AppConfig) -> Settings: if auth == "oauth2": _check_oauth2(issuer, jwks_url, client_id) timeout_ms = _whole_ms(config, POSTGRES_PREFIX + "timeout.ms", 5000) - port_text = _text(config, POSTGRES_PREFIX + "port", "5432") - if not port_text.isdigit() or int(port_text) <= 0: + port_value = config.get(POSTGRES_PREFIX + "port") + port = whole_number(5432 if port_value is None else port_value) + if port is None or not 1 <= port <= MAX_PORT: raise QuestionError(f"{POSTGRES_PREFIX}port must be a port number") + ssl = _switch(config, POSTGRES_PREFIX + "ssl", True) + _check_keep_alive(config) postgres: dict[str, Any] = { "host": _text(config, POSTGRES_PREFIX + "host", "127.0.0.1"), - "port": int(port_text), + "port": port, "dbname": _text(config, POSTGRES_PREFIX + "database", "mercury"), "user": _text(config, POSTGRES_PREFIX + "username") or None, "password": _text(config, POSTGRES_PREFIX + "password") or None, - "sslmode": "disable" if _text(config, POSTGRES_PREFIX + "ssl", "true").lower() == "false" else "require", + "sslmode": "require" if ssl else "disable", "connect_timeout": max(1, round(timeout_ms / 1000)), # the server-side bound on a statement, as the transcript audit store sets it "options": f"-c statement_timeout={timeout_ms}", @@ -330,8 +452,8 @@ def public(self) -> dict[str, Any]: def _check_wait(event: Mapping[str, Any], turn: Any) -> None: - """What a wait's event carries beyond an advice's - its turn, the ticket, the link, the expiry and the - waiting calls - or an AppException(400).""" + """What a wait's event carries beyond an advice's - its turn, the ticket, the link, the expiry (a time by the + one reader of both packs) and the waiting calls - or an AppException(400).""" if turn is None: raise AppException(400, "turn is required for an approval or a question") for name in ("ticket", "link", "expires_at"): @@ -340,6 +462,30 @@ def _check_wait(event: Mapping[str, Any], turn: Any) -> None: calls = event.get("calls") if not isinstance(calls, list) or not calls: raise AppException(400, "calls must be a non-empty list for an approval or a question") + if parse_iso(event["expires_at"]) is None: + raise AppException(400, "expires_at must be an ISO-8601 time") + + +def _turn(event: Mapping[str, Any]) -> int | None: + """An event's turn as the whole number it is - up to the largest the record's column holds - and None when + the event carries none; or an AppException(400).""" + given = event.get("turn") + if given is None: + return None + turn = whole_number(given) + if turn is None or turn > MAX_TURN: + raise AppException(400, "turn must be a whole number >= 0") + return turn + + +def _check_optional(event: Mapping[str, Any]) -> None: + """What an event may carry beyond what it must: details and requested_at as text, and requested_at a time by + the one reader of both packs - or an AppException(400).""" + for name in ("details", "requested_at"): + if event.get(name) is not None and not isinstance(event[name], str): + raise AppException(400, f"{name} must be text") + if event.get("requested_at") is not None and parse_iso(event["requested_at"]) is None: + raise AppException(400, "requested_at must be an ISO-8601 time") def validate_event(event: Any) -> dict[str, Any]: @@ -351,17 +497,15 @@ def validate_event(event: Any) -> dict[str, Any]: raise AppException(400, "kind must be one of approval, question, advice") for name in ("graph_id", "description", "correlation_id", "summary"): value = event.get(name) - if not isinstance(value, str) or not value.strip(): + # blank - nothing but the white space of the number rule - is as good as missing, in both packs + if not isinstance(value, str) or not _trimmed(value): raise AppException(400, f"{name} is required") - turn = event.get("turn") - if turn is not None and (isinstance(turn, bool) or not isinstance(turn, int) or turn < 0): - raise AppException(400, "turn must be a whole number >= 0") + turn = _turn(event) if kind in WAIT_KINDS: _check_wait(event, turn) - for name in ("details", "requested_at"): - if event.get(name) is not None and not isinstance(event[name], str): - raise AppException(400, f"{name} must be text") - return dict(event) + _check_optional(event) + # the turn as the whole number it is, however it was written - 2.0 and "2" are turn 2 in both packs + return dict(event) if turn is None else {**event, "turn": turn} def reply_request(link: str, ticket: str, decisions: Sequence[Mapping[str, Any]], who: str) -> tuple[str, dict[str, Any]]: @@ -399,6 +543,29 @@ def stream_cursor(last_event_id: str | None, since: str | None) -> int: return value +def page_size(text: str | None, default: int, most: int) -> int | None: + """The size of a page as a query names it: the default when it names none, else a whole number held between + 1 and the most a page takes - or None when the text spells no whole number.""" + if text is None or text == "": + return default + number = whole_number(text) + return None if number is None else min(most, max(1, number)) + + +def list_query(query: Mapping[str, str | None]) -> tuple[bool, int | None, int]: + """What ``GET /questions`` asks for - whether it pages back through the history, its cursor and its page + size - or an AppException(400). ``before`` (empty: the newest page) and ``since`` (none or empty: the + beginning) are numbers of the record, read as a row id and a stream's cursor are; ``limit`` is a whole + number.""" + paging = "before" in query + text = query.get("before" if paging else "since") + cursor = _record_number(text) if text else None + limit = page_size(query.get("limit"), LIST_LIMIT, LIST_LIMIT_MAX) + if limit is None or (text and cursor is None): + raise AppException(400, "since, before and limit must be whole numbers") + return paging, cursor if paging else cursor or 0, limit + + def page_since(rows: Sequence[Row], since: int, limit: int) -> dict[str, Any]: """The replay's page: the rows whose sequence passed the cursor, oldest change first, and the cursor to continue from.""" @@ -542,9 +709,9 @@ def _stamp(value: Any) -> str | None: if value is None: return None if isinstance(value, datetime): - return iso_utc(value) + return _utc_stamp(value) parsed = parse_iso(str(value)) - return iso_utc(parsed) if parsed else str(value) + return _utc_stamp(parsed) if parsed else str(value) def _json(value: Any) -> Any: @@ -805,9 +972,13 @@ async def question_health(headers: dict[str, str], _body: Body) -> Any: counts = await reader().counts() except Exception as exc: # noqa: BLE001 - health reports a store it cannot read by type counts = {"error": failure(exc)} + # a cursor past MAX_WHOLE is told in its digits, as text: the Node.js twin's host renders this map and + # renders no number that large, so both packs tell the same + cursor = _feed.cursor return { "service": INTAKE_ROUTE, "href": "http://127.0.0.1", "store": reader().name, "rows": counts, - "feed": _feed.cursor, "connected": _wakeups.connected, "auth": settings.auth, + "feed": cursor if cursor <= MAX_WHOLE else str(cursor), "connected": _wakeups.connected, + "auth": settings.auth, } # fmt: skip return "agent.question.inbox is running fine" @@ -823,7 +994,8 @@ class Identity: def _bearer(request: AsyncHttpRequest) -> str | None: scheme, _, token = (request.header("authorization") or "").partition(" ") - return token.strip() if scheme.lower() == "bearer" and token.strip() else None + token = _trimmed(token) + return token if scheme.lower() == "bearer" and token else None class OAuth2Verifier: @@ -966,14 +1138,6 @@ async def question_config(_headers: dict[str, str], _body: Body) -> Any: return _json_reply(ui_config(current_settings())) -def _whole(text: str | None, default: int) -> int: - if text is None or text == "": - return default - if not text.isdigit(): - raise ValueError(text) - return int(text) - - @preload(route=LIST_ROUTE, instances=INSTANCES, private=True) async def question_list(_headers: dict[str, str], body: Body) -> Any: """``GET /questions?since=&limit=``: every row that changed since the cursor, oldest change first, @@ -981,22 +1145,12 @@ async def question_list(_headers: dict[str, str], body: Body) -> Any: ``GET /questions?before=&limit=``: the history's older page, newest change first, and the cursor of the page before it - the infinite scroll.""" request = AsyncHttpRequest(body) - paging = "before" in request.query_parameters_map - before: int | None = None - since = 0 + paging, cursor, limit = list_query({name: request.query_parameter(name) for name in request.query_parameters_map}) + since = 0 if cursor is None else cursor try: - limit = min(LIST_LIMIT_MAX, max(1, _whole(request.query_parameter("limit"), LIST_LIMIT))) if paging: - text = request.query_parameter("before") - before = _whole(text, 0) if text else None - else: - since = _whole(request.query_parameter("since"), 0) - except ValueError: - raise AppException(400, "since, before and limit must be whole numbers") from None - try: - if paging: - older = await reader().before(before, limit) - return _json_reply(page_before(older, None, limit) | {"before": before}) + older = await reader().before(cursor, limit) + return _json_reply(page_before(older, None, limit) | {"before": cursor}) rows = await reader().since(since, limit) except Exception as exc: # noqa: BLE001 - a store that cannot be read is a 503 by type log.warning("The record could not be read - %s", failure(exc)) @@ -1012,13 +1166,18 @@ def _frame(row: Row) -> str: _streams: set[asyncio.Task[None]] = set() +def look_seconds(ping_ms: int) -> float: + """How often a quiet stream looks for its device: at the host's keep-alive interval, and every 30 seconds + when the host sends none or the interval is longer than a timer holds - the Node.js twin's would fire at once.""" + return ping_ms / 1000 if 0 < ping_ms <= MAX_TIMER_MS else 30.0 + + async def _follow(out: EventStreamWriter, since: int) -> None: """One device's stream: the rows since its cursor first, then every change the feed finds, until the device leaves (the edge closes the reply sink and ``connected`` turns false) or the application stops (the wake-ups close); the edge sends the keep-alive comments while nothing changes.""" queue = _wakeups.subscribe() - ping_ms = keep_alive_ms() - check_seconds = ping_ms / 1000 if ping_ms > 0 else 30.0 + check_seconds = look_seconds(keep_alive_ms()) try: for row in await reader().since(since, LIST_LIMIT_MAX): out.write_named("question", _frame(row)) @@ -1066,11 +1225,10 @@ async def transcript_list(_headers: dict[str, str], body: Body) -> Any: parsed = parse_iso(before) if parsed is None: raise AppException(400, "before must be an ISO-8601 time") - before = iso_utc(parsed) - try: - limit = min(TRANSCRIPTS_LIMIT_MAX, max(1, _whole(request.query_parameter("limit"), TRANSCRIPTS_LIMIT))) - except ValueError: - raise AppException(400, "limit must be a whole number") from None + before = _utc_stamp(parsed) + limit = page_size(request.query_parameter("limit"), TRANSCRIPTS_LIMIT, TRANSCRIPTS_LIMIT_MAX) + if limit is None: + raise AppException(400, "limit must be a whole number") try: rows = await reader().conversations(before, limit, request.query_parameter("correlation_id") or None, request.query_parameter("graph_id") or None) diff --git a/extensions/ask-person/README.md b/extensions/ask-person/README.md index a8560cb..4aeef56 100644 --- a/extensions/ask-person/README.md +++ b/extensions/ask-person/README.md @@ -86,11 +86,34 @@ is in memory, and when the record's database does not answer at start (the write | `kind` | `approval` (a call needs `approved`) or `question` (an ask row) | `advice` | | `graph_id`, `description`, `correlation_id`, `summary` | required text | required text | | `node` | optional: the loop node that waits | optional | -| `turn` | required, a whole number: the turn that waits | optional: the turn it follows | +| `turn` | required, a whole number from 0 to 2147483647 (below): the turn that waits | optional: the turn it follows | | `calls` | required: the approval block as the loop returned it | refused | -| `ttl` | required: the suspend node's time to live (`30m`, `12h`, `2d`, or whole seconds) | refused | +| `ttl` | required: the suspend node's time to live, a duration (`30m`, `12h`, `2d`, or whole seconds; below) | refused | | `details` | - | optional text, the body | -| `requested_at` | optional ISO-8601; the default is now | optional | +| `requested_at` | optional: an ISO-8601 time with `Z` or an offset (below); the default is now | optional | + +A number is read by one rule, the same in both packs and in the LLM helper: a **whole number** is a JSON number with a +whole value (`2`, or `2.0`, which one runtime cannot tell from it) or text of the ASCII digits 0 to 9, at most +9007199254740991 - the largest whole number both runtimes hold exactly - with the white space both runtimes' own trim +takes ignored around it and none inside; a sign, an underscore, a point or an exponent in text and the digits of +another script spell none. `turn` is a whole number of at most 2147483647 - the largest the record's `turn` column, a +32-bit `INTEGER`, holds - and the event carries it as the number, however the message wrote it. `ttl` is a +**duration**, more than zero: a whole number of seconds, or a whole number and, right after it, one of `ms`, `s`, `m`, +`h`, `d`; a duration is held in milliseconds, at most 9007199254740991 of them, and a wait ends before the year 10000 - +an expiry that neither pack can write is refused (`ttl must end before the year 10000`). `graph_id` and +`correlation_id` name the wait in its ticket, whose payload keeps Unicode as it is, in UTF-8: text with a lone +surrogate - half of a character, which no ticket can carry - is refused, for an advice too (`graph_id must be text +without a lone surrogate`). + +A **time** is read by one reader, the same in both packs: a date `YYYY-MM-DD`, an upper-case `T`, a time `HH:MM` or +`HH:MM:SS` with a fraction of one to nine digits at most, then `Z` or an offset `+HH:MM` / `-HH:MM`, and nothing +before or after it - no white space, no time without an offset, no other spelling of ISO 8601. The date is one the +calendar has, the hour 0 to 23, the minute and the second 0 to 59, the offset at most 23:59, and the year 0001 to +9999, as written and in UTC; the instant is read to the millisecond, a longer fraction cut. The event keeps +`requested_at` as the message wrote it, and a time the extension writes - `expires_at`, a row's stamps - is UTC to the +millisecond (`2026-11-21T09:12:04.118Z`). A required text is missing when it is **blank**: nothing but the white space +of the number rule, the same 24 characters in both packs. U+FEFF, U+0085 and U+001C to U+001F are not among them - +one runtime's own trim takes them and the other's does not - so here they are characters of a name. The function cross-checks `graph_id` against the engine's `x-graph-id` header when one is present. It answers `{ticket, link, expires_at, delivered, recorded}` for a wait and `{delivered, recorded}` for an advice, where @@ -103,7 +126,8 @@ its id as `graph_id` and the stage as `turn`; the record has one shape for an AI `v1..`: the payload `{"g": graph_id, "c": correlation_id, "t": turn, "k": kind, "e": expiry}` as canonical JSON (keys sorted, no spaces, Unicode kept) and its HMAC-SHA256 under `ask.ticket.key`, both base64url without -padding. Opaque and clean - no question text, no business data, no person - and stateless: the reply endpoint verifies +padding; the expiry is `expires_at` in whole seconds from 1970-01-01T00:00:00Z, rounded down - before 1970 too. +Opaque and clean - no question text, no business data, no person - and stateless: the reply endpoint verifies it with the key alone, so every channel works without a store. `ask.ticket.previous-key` verifies the tickets issued before a rotation. A ticket is accepted as many times as it is presented: single use is the engine's at-most-once resume, and the second presentation gets `nothing waiting`. An expired ticket (410) is refused without a call to the @@ -111,7 +135,11 @@ engine; a malformed one or another version is a 400, one no key signs a 403. A t well-formed only with its three parts, the payload and the signature each canonical base64url without padding - the alphabet from start to end, no newline, no stray character, no bits left over in the last one - and the signature as long as the MAC, so any other spelling is malformed whatever it resembles and a 403 is a well-formed ticket that no -key signs. +key signs. The payload has one spelling too: under a valid signature the signed bytes are the canonical JSON of the +five fields and nothing else - a graph id and a correlation id that are not empty and hold no lone surrogate, a turn +from 0, a wait's kind, an expiry, the two numbers whole and no larger in size than 9007199254740991 - so a float for a +whole number, an escape the canonical form does not write, a key twice, a space, another order of the keys or bytes +that are not UTF-8 are malformed whoever signed them. ## The reply page and endpoint @@ -168,8 +196,14 @@ The writes are order-independent, so `question.audit` may run several instances upserted unless the row holds a newer `requested_at` (an older message landing late never overwrites a newer one), an advice is appended, and an answer applies while the row is open or when the engine accepted the decision - the first accepted decision stands, a late `nothing waiting` never overwrites it. The sweeper (`ask.audit.sweep`) marks open -waits past their expiry `expired`. A question joins its transcript (the LLM helper's `transcript` table) by -`correlation_id` and `graph_id`. Rows are never deleted here; `schema/purge.sql` is the installation's retention. +waits past their expiry `expired`. Two times are compared as the instants they name, in the memory store as in +PostgreSQL: a `requested_at` written at an offset or to the minute is in its place, whatever its text sorts as. A +question joins its transcript (the LLM helper's `transcript` table) by `correlation_id` and `graph_id`. Rows are never +deleted here; `schema/purge.sql` is the installation's retention. +`id` and `seq` are `BIGINT`: a row is told by the numbers it has - in the recorder's answer and in its log line - past +9007199254740991 too. `turn` is a 32-bit `INTEGER`, the reason a message's turn is at most 2147483647. `message`, +`decisions` and `outcome` are given to the store as compact JSON with every digit of a whole number past +9007199254740991 - one in a waiting call's input, for instance - in both packs. **The contract** (`QuestionStore` in `ask_person.py`) is published so a field keeps the record on another database: `record(event, now)` (a wait upserted or an advice appended, the row as it stands), `answer(key, decisions, who, state, @@ -201,11 +235,24 @@ record under the store's read role; it is the backend of the React UI maintained | `ask.audit.instances` | `1` | the recorder's workers; more is safe | | `ask.audit.timeout` | `5s` | how long a write may take before the hold or the reply goes on without it | +A setting is read by the rule of the message's numbers, whether a YAML file holds the value or a `${NAME:default}` +reference or a `-D` override gives it as text: `ask.audit.instances`, `.port` and `.timeout.ms` are whole numbers; the +timeouts and `ask.audit.sweep` are durations - seconds, or `ms`, `s`, `m`, `h`, `d` right after the number - more than +zero. A setting that sets a timer - a timeout, `ask.audit.sweep`, `.timeout.ms` - takes at most 2147483647 ms (about +24.8 days), the longest delay both runtimes' timers hold, and `.port` is 1 to 65535. A switch (`ask.enabled`, +`ask.audit.postgres.ssl`) is `true` or `false`, the boolean or the text in any letter case; no value and an empty one +are the default; any other value - `yes`, `on`, `1` - stops the boot by the key's name instead of being read as off. So +does a number or a duration that is not one. A setting's text - a key, a name, a URL, a mode - loses the white space of +the number rule around it and no other character. + ## Tests `tests/test_ask_person.py` runs the shared vectors (`tests/vectors/ask-person-vectors.json`: the ticket issued, verified, -tampered, expired and rotated; the message validated and the event built; the re-advice and the resume requests; the -outcomes; the row a message becomes, the state an answer leaves and the record's transitions) and drives the function +tampered, expired and rotated, and the payloads a key holder signed in another spelling; the message validated and the +event built; the re-advice and the resume requests; the outcomes; the row a message becomes, the state an answer leaves +and the record's transitions; a number, a duration and a switch as the one rule reads them; a time as the one reader +reads it, the white space around a text, and whole numbers past 9007199254740991 as the record is given them) and +drives the function and the page in-process: channels that take, refuse and miss the event, the record written before they are told; the reply endpoint against a fake engine, the answer recorded with who decided; the two auth modes with a signed token and the page's configuration; the PostgreSQL store's statements on a recording fake of the pool, and - gated on diff --git a/extensions/ask-person/ask_person.py b/extensions/ask-person/ask_person.py index 2de2f88..de3a639 100644 --- a/extensions/ask-person/ask_person.py +++ b/extensions/ask-person/ask_person.py @@ -146,7 +146,35 @@ AUDIT_TIMEOUT = "ask.audit.timeout" MISSING_POSTGRES = "ask.audit is postgres but psycopg is not installed - pip install 'mercury-composable[postgres]'" -DURATION = re.compile(r"^(\d+)\s*(ms|s|m|h|d)?$") +# how a number is read, the same in both packs and in every extension: the largest whole number both +# packs hold exactly (2**53 - 1) - above it the Node.js twin's numbers round, and the twins would read +# two different numbers from one message +MAX_WHOLE = 9007199254740991 +# the longest wait both packs' timers hold, in milliseconds (2**31 - 1, about 24.8 days): the Node.js +# twin's timers keep a delay in 32 bits with a sign and fire at once on a longer one, so a setting +# that sets a timer takes no more, here as there +MAX_TIMER_MS = 2147483647 +# the highest port a connection can name +MAX_PORT = 65535 +# the largest turn the question record holds: its turn column is a 32-bit INTEGER (schema/postgres.sql) +MAX_TURN = 2147483647 +# the white space ignored around a number and a duration: the characters Python's str.strip() and +# JavaScript's trim() both take for white space, so neither pack accepts a character the other refuses +_SPACE = r"[\t-\r \xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]" +# the same 24 characters as a text, to take off the ends of a text: a required text is blank and a +# setting's text is trimmed by these and no other. Each runtime's own trim takes a few more - this +# one's U+001C to U+001F and U+0085, the Node.js twin's U+FEFF - which here are characters of a name +_SPACES = "\t\n\x0b\x0c\r \xa0\u1680" + "".join(map(chr, range(0x2000, 0x200B))) + "\u2028\u2029\u202f\u205f\u3000" +# the digits 0 to 9 and no other, by flag: Python's own \d takes the digits of every script +WHOLE = re.compile(rf"^{_SPACE}*(\d+){_SPACE}*$", re.ASCII) +DURATION = re.compile(rf"^{_SPACE}*(\d+)(ms|s|m|h|d)?{_SPACE}*$", re.ASCII) +# a time as both packs read one: a date, an upper-case T, a time to the minute or to the second - the +# second with a fraction of one to nine digits at most - and Z or an offset in hours and minutes +ISO_TIME = re.compile( + r"(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(?:\.(\d{1,9}))?)?(?:Z|([+-])(\d\d):(\d\d))", re.ASCII +) +# where the whole seconds of an expiry are counted from +_EPOCH = datetime(1970, 1, 1, tzinfo=UTC) # the base64url alphabet without padding - a ticket part outside it is malformed, never decoded leniently BASE64URL = re.compile(r"^[A-Za-z0-9_-]+$") UNIT_MS = {"ms": 1, "s": 1000, "m": 60_000, "h": 3_600_000, "d": 86_400_000} @@ -180,34 +208,122 @@ def __init__(self, status: int, message: str) -> None: # --- durations and times ---------------------------------------------------------------------- +def _number_text(value: Any) -> str | None: + """What a number is read from: a string as written, or the digits of a JSON number with a + whole value - an integer, or a float, which the Node.js twin cannot tell from one. None for + anything else: a boolean, a fraction, a number beyond MAX_WHOLE.""" + if isinstance(value, str): + return value + if isinstance(value, float) and value.is_integer(): + value = int(value) + if isinstance(value, bool) or not isinstance(value, int) or abs(value) > MAX_WHOLE: + return None + return str(value) + + +def _digits(digits: str) -> int | None: + """The whole number a run of ASCII digits spells, or None above MAX_WHOLE - told by the count + of its digits first, so a run of any length is judged without being converted.""" + significant = digits.lstrip("0") + if len(significant) > len(str(MAX_WHOLE)): + return None + number = int(significant or "0") + return number if number <= MAX_WHOLE else None + + +def whole_number(value: Any) -> int | None: + """The whole number a value spells - a JSON number with a whole value, or ASCII digits with + white space around them at most - up to MAX_WHOLE; None when it spells none: a sign, an + underscore, a point or an exponent in text, a digit of another script.""" + text = _number_text(value) + match = WHOLE.fullmatch(text) if text is not None else None + return _digits(match.group(1)) if match else None + + def duration_ms(value: Any) -> int | None: """Milliseconds from a whole number of seconds or a duration such as 500ms, 30m, 12h or - 2d; None when the value is neither.""" + 2d - such a number and, right after it, one of ms, s, m, h, d - up to MAX_WHOLE + milliseconds; None when the value is neither.""" + text = _number_text(value) + match = DURATION.fullmatch(text) if text is not None else None + count = _digits(match.group(1)) if match else None + if match is None or count is None: + return None + ms = count * UNIT_MS[match.group(2) or "s"] + return ms if ms <= MAX_WHOLE else None + + +def switch_value(value: Any, default: bool) -> bool | None: + """What a switch is set to: the boolean, or the text true or false in any letter case; no + value and an empty one are the default. None for any other value - it is never read as off.""" + if value is None or value == "": + return default if isinstance(value, bool): + return value + lowered = value.lower() if isinstance(value, str) else "" + return lowered == "true" if lowered in ("true", "false") else None + + +def _trimmed(text: str) -> str: + """A text without the white space around it - the 24 characters of the number rule, the same in + both packs, where str.strip() alone takes a few more. A blank text leaves nothing.""" + return text.strip(_SPACES) + + +def parse_iso(text: str) -> datetime | None: + """An ISO-8601 time with an offset or ``Z``, as a UTC datetime; None when it is not one. One + reader in both packs: a date ``YYYY-MM-DD``, an upper-case ``T``, a time ``HH:MM`` or + ``HH:MM:SS`` - the second with a fraction of one to nine digits at most - then ``Z`` or + ``+HH:MM`` / ``-HH:MM``, and nothing before or after it; a date the calendar has, in the years + 0001 to 9999 as written and in UTC. The instant is read to the millisecond: a longer fraction + is cut, never rounded.""" + match = ISO_TIME.fullmatch(text) + if match is None: return None - if isinstance(value, int): - return value * 1000 if value >= 0 else None - if not isinstance(value, str): + year, month, day, hour, minute = (int(part) for part in match.group(1, 2, 3, 4, 5)) + second, fraction, sign = match.group(6, 7, 8) + offset_hours, offset_minutes = (int(part or 0) for part in match.group(9, 10)) + if offset_hours > 23 or offset_minutes > 59: return None - match = DURATION.fullmatch(value.strip()) - if not match: + offset = timedelta(hours=offset_hours, minutes=offset_minutes) + millisecond = int((fraction or "").ljust(3, "0")[:3]) + try: + # datetime refuses a date the calendar does not have and a time the clock does not + written = datetime(year, month, day, hour, minute, int(second or 0), millisecond * 1000, tzinfo=UTC) + return written + offset if sign == "-" else written - offset + # a ValueError is the date or the time; an OverflowError the instant, outside the years in UTC + except (ValueError, OverflowError): return None - unit = match.group(2) or "s" - return int(match.group(1)) * UNIT_MS[unit] -def parse_iso(text: str) -> datetime | None: - """An ISO-8601 time with an offset or ``Z``, as a UTC datetime; None when it is not one.""" - candidate = text.strip() - if candidate.endswith(("Z", "z")): - candidate = candidate[:-1] + "+00:00" +def _utc_stamp(moment: datetime) -> str: + """The text both packs write for an instant: UTC, to the millisecond, the year in four digits - + spelled out here, since strftime leaves a year before 1000 unpadded on some platforms.""" + utc = (moment if moment.tzinfo is not None else moment.replace(tzinfo=UTC)).astimezone(UTC) + return ( + f"{utc.year:04d}-{utc.month:02d}-{utc.day:02d}T{utc.hour:02d}:{utc.minute:02d}:{utc.second:02d}" + f".{utc.microsecond // 1000:03d}Z" + ) + + +def _earlier(left: str, right: str) -> bool: + """True when a time is before another: by their instants, as the reference store compares two + stamps - so a time written at an offset or to the minute is in its place - and by their texts + when one of them is no time.""" + first, second = parse_iso(left), parse_iso(right) + if first is None or second is None: + return left < right + return first < second + + +def _expiry_of(requested_at: str, ttl_ms: int) -> datetime | None: + """When a wait expires - ``requested_at`` plus its ``ttl`` - or None when that is not before + the year 10000: a time neither pack can write.""" + requested = parse_iso(requested_at) or datetime.now(UTC) try: - value = datetime.fromisoformat(candidate) - except ValueError: + return requested + timedelta(milliseconds=ttl_ms) + except OverflowError: return None - if value.tzinfo is None: - value = value.replace(tzinfo=UTC) - return value.astimezone(UTC) # --- configuration ---------------------------------------------------------------------------- @@ -241,16 +357,16 @@ class Settings: def _text(config: AppConfig, key: str, default: str = "") -> str: """A text setting; an unset key (or one cleared to None) takes the default.""" value = config.get(key) - return default if value is None else str(value).strip() + return default if value is None else _trimmed(str(value)) def _flag(config: AppConfig, key: str, default: bool) -> bool: - value = config.get(key) - if value is None: - return default - if isinstance(value, bool): - return value - return str(value).strip().lower() in ("true", "yes", "on", "1") + """A switch of the configuration, or an AskError naming the key: a value that is neither true + nor false stops the boot instead of leaving the switch off.""" + switch = switch_value(config.get(key), default) + if switch is None: + raise AskError(f"{key} must be true or false") + return switch def _names(value: Any) -> list[str]: @@ -258,7 +374,7 @@ def _names(value: Any) -> list[str]: if value is None: return [] items = value if isinstance(value, list) else str(value).split(",") - return [str(item).strip() for item in items if str(item).strip()] + return [name for name in (_trimmed(str(item)) for item in items) if name] def _pairs(value: Any, key_name: str, value_name: str, setting: str) -> dict[str, str]: @@ -271,45 +387,49 @@ def _pairs(value: Any, key_name: str, value_name: str, setting: str) -> dict[str for item in value: if not isinstance(item, Mapping) or not item.get(key_name) or not item.get(value_name): raise AskError(f"{setting} entries need {key_name} and {value_name}") - result[str(item[key_name]).strip()] = str(item[value_name]).strip() + result[_trimmed(str(item[key_name]))] = _trimmed(str(item[value_name])) return result for part in str(value).split(","): - if not part.strip(): + if not _trimmed(part): continue - key, sep, target = part.partition("=") - if not sep or not key.strip() or not target.strip(): + key, sep, target = (_trimmed(piece) for piece in part.partition("=")) + if not sep or not key or not target: raise AskError(f"{setting} takes {key_name}={value_name} pairs") - result[key.strip()] = target.strip() + result[key] = target return result def _timeout(config: AppConfig, key: str, default: str) -> int: + """A setting that sets a timer: a duration of more than nothing and of no more than a timer + holds in both packs.""" value = config.get(key) ms = duration_ms(default if value is None else value) - if ms is None or ms <= 0: + if ms is None or ms <= 0 or ms > MAX_TIMER_MS: raise AskError(f"{key} must be {DURATION_RULE} > 0") return ms -def _whole(config: AppConfig, key: str, default: int, minimum: int) -> int: - """A whole number >= ``minimum`` (a count of instances, a number of milliseconds).""" +def _whole(config: AppConfig, key: str, default: int, minimum: int, maximum: int = MAX_WHOLE) -> int: + """A whole number >= ``minimum`` (a count of instances, a number of milliseconds) and, for a + key that sets a timer, of no more than a timer holds.""" value = config.get(key) - text = str(default if value is None else value).strip() - if not text.isdigit() or int(text) < minimum: + number = whole_number(default if value is None else value) + if number is None or number < minimum or number > maximum: raise AskError(f"{key} must be a whole number >= {minimum}") - return int(text) + return number def _audit_postgres(config: AppConfig, timeout_ms: int) -> dict[str, Any]: """The connection keys of the question record's PostgreSQL store - the transcript audit store's keys under the ``ask.audit.postgres.`` prefix; the password a reference, never logged.""" - port_text = _text(config, AUDIT_POSTGRES_PREFIX + "port", "5432") - if not port_text.isdigit() or int(port_text) <= 0: + port_value = config.get(AUDIT_POSTGRES_PREFIX + "port") + port = whole_number(5432 if port_value is None else port_value) + if port is None or not 1 <= port <= MAX_PORT: raise AskError(f"{AUDIT_POSTGRES_PREFIX}port must be a port number") - ssl = _text(config, AUDIT_POSTGRES_PREFIX + "ssl", "true").lower() != "false" + ssl = _flag(config, AUDIT_POSTGRES_PREFIX + "ssl", True) settings: dict[str, Any] = { "host": _text(config, AUDIT_POSTGRES_PREFIX + "host", "127.0.0.1"), - "port": int(port_text), + "port": port, "dbname": _text(config, AUDIT_POSTGRES_PREFIX + "database", "mercury"), "user": _text(config, AUDIT_POSTGRES_PREFIX + "username") or None, "password": _text(config, AUDIT_POSTGRES_PREFIX + "password") or None, @@ -347,7 +467,7 @@ def load_settings(config: AppConfig) -> Settings: reply_url = _text(config, REPLY_URL).rstrip("/") auth = _text(config, REPLY_AUTH, "none").lower() audit = _text(config, AUDIT, "memory").lower() - postgres_timeout_ms = _whole(config, AUDIT_POSTGRES_PREFIX + "timeout.ms", 5000, 1) + postgres_timeout_ms = _whole(config, AUDIT_POSTGRES_PREFIX + "timeout.ms", 5000, 1, MAX_TIMER_MS) settings = Settings( enabled=enabled, channels=tuple(_names(config.get(CHANNELS))), @@ -435,6 +555,18 @@ def canonical_json(value: Any) -> str: return json.dumps(value, separators=(",", ":"), sort_keys=True, ensure_ascii=False) +def _carried(text: Any) -> bool: + """True for text a ticket's payload can carry: not empty, and every character one UTF-8 can + write - a lone surrogate is half of a character, and the canonical form keeps Unicode as it is.""" + if not isinstance(text, str) or not text: + return False + try: + text.encode("utf-8") + except UnicodeEncodeError: + return False + return True + + def _mac(payload: bytes, key: bytes) -> bytes: return hmac.new(key, payload, hashlib.sha256).digest() @@ -450,24 +582,43 @@ def issue_ticket(payload: Mapping[str, Any], key: bytes) -> str: return f"{TICKET_VERSION}.{_b64u(encoded)}.{_b64u(_mac(encoded, key))}" +def _whole_json(value: Any) -> bool: + """True for a JSON integer both packs hold exactly - never a boolean, a float or text.""" + return isinstance(value, int) and not isinstance(value, bool) and abs(value) <= MAX_WHOLE + + def _payload_is_valid(payload: Any) -> bool: + """A wait's payload: the five fields and no other - a graph id and a correlation id a ticket + can carry, a turn from 0, a wait's kind and an expiry, the numbers integers both packs hold.""" if not isinstance(payload, dict) or set(payload) != {"g", "c", "t", "k", "e"}: return False graph_id, cid, turn, kind, expiry = (payload[k] for k in ("g", "c", "t", "k", "e")) return ( - isinstance(graph_id, str) - and bool(graph_id) - and isinstance(cid, str) - and bool(cid) - and isinstance(turn, int) - and not isinstance(turn, bool) + _carried(graph_id) + and _carried(cid) + and _whole_json(turn) and turn >= 0 and kind in WAIT_KINDS - and isinstance(expiry, int) - and not isinstance(expiry, bool) + and _whole_json(expiry) ) +def _payload_of(payload_bytes: bytes) -> dict[str, Any] | None: + """The payload a signed part spells, or None when it spells none: the bytes are the canonical + JSON of a wait's payload and nothing else - a payload has one spelling, as the ticket's parts + have, so a float for a whole number, a key twice, a space, an escape the canonical form does + not write or bytes that are not UTF-8 are refused whoever signed them.""" + try: + payload = json.loads(payload_bytes.decode("utf-8")) + # the JSON decoder's own error and a UnicodeDecodeError are both ValueErrors; nesting too deep + # for the decoder is its RecursionError + except (ValueError, RecursionError): + return None + if not _payload_is_valid(payload): + return None + return payload if canonical_json(payload).encode("utf-8") == payload_bytes else None + + # what the invoker sees when a ticket's parts, their encoding or the payload cannot be read - the # text is pinned by the shared vectors _TICKET_MALFORMED = "Ticket is malformed" @@ -478,7 +629,9 @@ def verify_ticket(ticket: str, keys: Sequence[bytes], now: float) -> dict[str, A malformed or of another version, 403 when no key signs it, 410 when it has expired. A ticket is well-formed when it has the three parts, its payload and its signature are canonical base64url without padding and the signature is as long as the MAC; one that is not is - malformed whatever it resembles, so a 403 is a well-formed ticket that no key signs.""" + malformed whatever it resembles, so a 403 is a well-formed ticket that no key signs. The + payload under a valid signature is the canonical JSON of a wait's five fields or it is + malformed too.""" parts = ticket.split(".") if len(parts) != 3 or not all(parts): raise TicketError(400, _TICKET_MALFORMED) @@ -491,11 +644,8 @@ def verify_ticket(ticket: str, keys: Sequence[bytes], now: float) -> dict[str, A raise TicketError(400, _TICKET_MALFORMED) if not any(hmac.compare_digest(_mac(payload_bytes, key), mac) for key in keys): raise TicketError(403, "Ticket signature is invalid") - try: - payload = json.loads(payload_bytes.decode("utf-8")) - except ValueError as exc: # the JSON decoder's own error and a UnicodeDecodeError are both ValueErrors - raise TicketError(400, _TICKET_MALFORMED) from exc - if not _payload_is_valid(payload): + payload = _payload_of(payload_bytes) + if payload is None: raise TicketError(400, _TICKET_MALFORMED) if payload["e"] < now: raise TicketError(410, "Ticket expired") @@ -522,12 +672,14 @@ class Message: def _required_text(body: Mapping[str, Any], name: str) -> str: + """A text the message must carry: blank - nothing but the white space of the number rule - is + as good as missing, by the same characters in both packs.""" value = body.get(name) if value is None: raise AppException(400, f"{name} is required") if not isinstance(value, str): raise AppException(400, f"{name} must be text") - if not value.strip(): + if not _trimmed(value): raise AppException(400, f"{name} is required") return value @@ -541,14 +693,47 @@ def _optional_text(body: Mapping[str, Any], name: str) -> str | None: return value +def _ticket_text(body: Mapping[str, Any], name: str) -> str: + """A required text that names the wait in its ticket - the graph id, the correlation id - or + an AppException(400): a lone surrogate is half of a character, which no ticket can carry.""" + value = _required_text(body, name) + if not _carried(value): + raise AppException(400, f"{name} must be text without a lone surrogate") + return value + + def _turn(value: Any, required: bool) -> int | None: if value is None: if required: raise AppException(400, "turn is required for an approval or a question") return None - if isinstance(value, bool) or not isinstance(value, int) or value < 0: + turn = whole_number(value) + if turn is None or turn > MAX_TURN: # a turn the record's column cannot hold is no turn raise AppException(400, "turn must be a whole number >= 0") - return value + return turn + + +# a wait whose expiry - requested_at plus ttl - is a time neither pack can write +_TTL_ENDS_TOO_LATE = "ttl must end before the year 10000" + + +def _ttl_ms(body: Mapping[str, Any], requested_at: str) -> int: + """A wait's ttl in milliseconds - a duration of more than nothing, which ends before the year + 10000 - or an AppException(400) naming the rule.""" + if "ttl" not in body: + raise AppException(400, "ttl is required for an approval or a question") + ttl_ms = duration_ms(body["ttl"]) + if ttl_ms is None or ttl_ms <= 0: + raise AppException(400, f"ttl must be {DURATION_RULE} > 0") + if _expiry_of(requested_at, ttl_ms) is None: + raise AppException(400, _TTL_ENDS_TOO_LATE) + return ttl_ms + + +def _as_sent(ttl: Any) -> Any: + """A wait's ttl as the event carries it: as the message wrote it, but a float with a whole + value as that whole number - all the Node.js twin sees of one, so both packs send the same.""" + return int(ttl) if isinstance(ttl, float) else ttl def validate_message(body: Any) -> Message: @@ -559,9 +744,9 @@ def validate_message(body: Any) -> Message: kind = body.get("kind") if kind not in KINDS: raise AppException(400, "kind must be one of approval, question, advice") - graph_id = _required_text(body, "graph_id") + graph_id = _ticket_text(body, "graph_id") description = _required_text(body, "description") - correlation_id = _required_text(body, "correlation_id") + correlation_id = _ticket_text(body, "correlation_id") summary = _required_text(body, "summary") node = _optional_text(body, "node") requested_at_text = _optional_text(body, "requested_at") @@ -594,11 +779,7 @@ def validate_message(body: Any) -> Message: for call in calls) ): raise AppException(400, "calls must be a non-empty list of the waiting calls, each with an id") - if "ttl" not in body: - raise AppException(400, "ttl is required for an approval or a question") - ttl_ms = duration_ms(body["ttl"]) - if ttl_ms is None or ttl_ms <= 0: - raise AppException(400, f"ttl must be {DURATION_RULE} > 0") + ttl_ms = _ttl_ms(body, requested_at) return Message( kind=kind, graph_id=graph_id, @@ -609,7 +790,7 @@ def validate_message(body: Any) -> Message: node=node, turn=turn, calls=[dict(call) for call in calls], - ttl=body["ttl"], + ttl=_as_sent(body["ttl"]), ttl_ms=ttl_ms, details=None, ) @@ -621,7 +802,8 @@ def ticket_payload(message: Message, expires_at: datetime) -> dict[str, Any]: "c": message.correlation_id, "t": message.turn, "k": message.kind, - "e": int(expires_at.timestamp()), + # the expiry in whole seconds, the floor - before 1970 too, where int() would cut toward zero + "e": (expires_at - _EPOCH) // timedelta(seconds=1), } @@ -647,10 +829,11 @@ def build_event(message: Message, key: bytes, reply_url: str) -> dict[str, Any]: event["ttl"] = message.ttl event["requested_at"] = message.requested_at if message.kind in WAIT_KINDS and message.ttl_ms is not None: - requested = parse_iso(message.requested_at) or datetime.now(UTC) - expires_at = requested + timedelta(milliseconds=message.ttl_ms) + expires_at = _expiry_of(message.requested_at, message.ttl_ms) + if expires_at is None: # a message validate_message did not see + raise AppException(400, _TTL_ENDS_TOO_LATE) ticket = issue_ticket(ticket_payload(message, expires_at), key) - event["expires_at"] = iso_utc(expires_at) + event["expires_at"] = _utc_stamp(expires_at) event["ticket"] = ticket event["link"] = f"{reply_url.rstrip('/')}/ask/{ticket}" return event @@ -893,7 +1076,7 @@ async def record(self, event: Mapping[str, Any], now: str) -> Row: # NOSONAR - key = wait_key(event) existing = self._rows.get(self._keys[key]) if key is not None and key in self._keys else None if existing is not None: - if fields["requested_at"] < existing.requested_at: + if _earlier(fields["requested_at"], existing.requested_at): return existing # an older message landing late never overwrites a newer row row = replace(existing, seq=self._bump(), **fields) else: @@ -923,7 +1106,7 @@ async def expire(self, now: str) -> list[Row]: # NOSONAR - async by contract: t changed: list[Row] = [] # no copy: a change replaces the value under the key being visited, and adds or removes none for row in self._rows.values(): - if row.state == "open" and row.kind in WAIT_KINDS and row.expires_at and row.expires_at < now: + if row.state == "open" and row.kind in WAIT_KINDS and row.expires_at and _earlier(row.expires_at, now): row = replace(row, seq=self._bump(), state="expired", updated_at=now) self._rows[row.id] = row changed.append(row) @@ -990,9 +1173,9 @@ def _stamp(value: Any) -> str | None: if value is None: return None if isinstance(value, datetime): - return iso_utc(value) + return _utc_stamp(value) parsed = parse_iso(str(value)) - return iso_utc(parsed) if parsed else str(value) + return _utc_stamp(parsed) if parsed else str(value) def _json(value: Any) -> Any: @@ -1279,7 +1462,15 @@ class Identity: def _bearer(request: AsyncHttpRequest) -> str | None: value = request.header("authorization") or "" scheme, _, token = value.partition(" ") - return token.strip() if scheme.lower() == "bearer" and token.strip() else None + token = _trimmed(token) + return token if scheme.lower() == "bearer" and token else None + + +def _same_secret(left: str, right: str) -> bool: + """Two secrets compared in constant time, as the bytes UTF-8 writes them - as the Node.js twin + compares them: hmac.compare_digest alone refuses text past ASCII, and a bearer is whatever a + request carries.""" + return hmac.compare_digest(left.encode("utf-8", "surrogatepass"), right.encode("utf-8", "surrogatepass")) class OAuth2Verifier: @@ -1372,7 +1563,7 @@ async def identify( access token (the page obtains one by Authorization Code with PKCE, a channel app's device through its own UI).""" bearer = _bearer(request) - if allow_app and settings.app_token and bearer and hmac.compare_digest(bearer, settings.app_token): + if allow_app and settings.app_token and bearer and _same_secret(bearer, settings.app_token): return Identity(decided_by or "channel", "app") if settings.auth == "none": return Identity(decided_by or "anonymous", "none") @@ -1621,7 +1812,8 @@ async def _engine(request: EngineRequest, timeout_ms: int) -> tuple[int, dict[st request.url, json=request.body, headers=headers, - timeout=aiohttp.ClientTimeout(total=timeout_ms / 1000 + 1), + # a second more than the engine's own allowance, and never more than a timer holds + timeout=aiohttp.ClientTimeout(total=min(timeout_ms + 1000, MAX_TIMER_MS) / 1000), ) as response: text = await response.text() return map_outcome(response.status, text, None) diff --git a/tests/test_agent_question.py b/tests/test_agent_question.py index 4c78192..3ac7c54 100644 --- a/tests/test_agent_question.py +++ b/tests/test_agent_question.py @@ -1,8 +1,11 @@ """The agent-question app (extensions/agent-question/agent_question.py). The shared vectors first (tests/vectors/agent-question-vectors.json): the event the intake accepts or refuses, the -request the automated click sends, the pages the replay and the history read, and the row id and the cursor a -request names - digits the record holds, or the 400. Then the app in-process as the reader of +request the automated click sends, the pages the replay and the history read, the row id and the cursor a +request names - digits the record holds, or the 400 - what GET /questions asks for, a page size, rows past the +whole numbers a double holds told by the numbers they have, a number, a duration and a switch read by the one +rule of both packs, a time read by their one reader and the white space around a text. Then the app in-process as +the reader of the question record the main flow keeps: the intake waking the feed, the replay and the history pages and the stream over the host, the transcripts browsed, a decision forwarded to a fake reply endpoint under the app's bearer and the row re-read as the recorder left it, the two auth modes with the UI's configuration, the PostgreSQL reader's statements @@ -150,8 +153,9 @@ def _case(section: str, name: str) -> dict[str, Any]: def test_the_vector_file_is_the_shared_contract() -> None: assert VECTORS["contract"] == "agent-question" - assert VECTORS["version"] == 4 - for section in ("intake_cases", "click_cases", "feed_cases", "row_id_cases", "cursor_cases"): + assert VECTORS["version"] == 6 + for section in ("intake_cases", "click_cases", "feed_cases", "row_id_cases", "cursor_cases", "number_cases", + "switch_cases", "list_cases", "page_size_cases", "exact_cases", "time_cases", "text_cases"): assert VECTORS[section], section @@ -231,6 +235,164 @@ def test_cursor_cases(name: str) -> None: assert (refused.value.status, refused.value.message) == (case["status"], case["error"]) +@pytest.mark.parametrize("name", _names("number_cases")) +def test_number_cases(name: str) -> None: + """A value read as a whole number and as a duration: the one rule of both packs and of every extension.""" + case = _case("number_cases", name) + assert aq.whole_number(case["value"]) == case["whole"] + assert aq.duration_ms(case["value"]) == case["duration_ms"] + + +@pytest.mark.parametrize("name", _names("switch_cases")) +def test_switch_cases(name: str) -> None: + """A switch: true or false, the default for no value and an empty one, and None - refused - for any other.""" + case = _case("switch_cases", name) + on, off = (True, False) if case["switch"] == "default" else (case["switch"], case["switch"]) + assert aq.switch_value(case["value"], True) is on + assert aq.switch_value(case["value"], False) is off + + +@pytest.mark.parametrize("name", _names("list_cases")) +def test_list_cases(name: str) -> None: + """What GET /questions asks for, from its parameters as the request wrote them.""" + case = _case("list_cases", name) + if "paging" in case: + paging, cursor, limit = aq.list_query(case["query"]) + asked = {"paging": paging, "cursor": None if cursor is None else str(cursor), "limit": limit} + assert asked == {k: case[k] for k in ("paging", "cursor", "limit")} + else: + with pytest.raises(aq.AppException) as refused: + aq.list_query(case["query"]) + assert (refused.value.status, refused.value.message) == (case["status"], case["error"]) + + +@pytest.mark.parametrize("name", _names("page_size_cases")) +def test_page_size_cases(name: str) -> None: + case = _case("page_size_cases", name) + assert aq.page_size(case["limit"], case["default"], case["most"]) == case["size"] + + +_EPOCH = datetime(1970, 1, 1, tzinfo=UTC) + + +class _RecordingReader: + """A reader that keeps the instant the transcripts were asked for, and holds no conversation.""" + + name = "recording" + + def __init__(self) -> None: + self.asked: list[str | None] = [] + + async def conversations(self, before: str | None, _limit: int, _correlation_id: str | None, + _graph_id: str | None) -> list[dict[str, Any]]: + self.asked.append(before) + return [] + + +@pytest.mark.parametrize("name", _names("time_cases")) +async def test_time_cases(name: str, monkeypatch: pytest.MonkeyPatch) -> None: + """A time a caller supplies, by the one reader of both packs: the instant to the millisecond and the text + written back for it - which is what the transcripts' before hands the store - or no time at all, the 400.""" + case = _case("time_cases", name) + moment = aq.parse_iso(case["text"]) + reader = _RecordingReader() + monkeypatch.setattr(aq, "_reader", reader) + request = aq.AsyncHttpRequest().set_query_parameter("before", case["text"]).to_map() + if case["ms"] is None: + assert moment is None + assert aq._stamp(case["text"]) == case["text"], "a stamp the store gave as text is kept as it came" + else: + assert (moment - _EPOCH) // timedelta(milliseconds=1) == case["ms"] + assert aq._stamp(case["text"]) == case["stamp"] + if case["ms"] is None and case["text"]: + with pytest.raises(aq.AppException) as refused: + await aq.transcript_list({}, request) + assert (refused.value.status, refused.value.message) == (400, "before must be an ISO-8601 time") + assert reader.asked == [] + else: + # the store is asked by the text written for the instant; an empty before is no cursor + reply = await aq.transcript_list({}, request) + assert reply.get_status() == 200 + assert reader.asked == [case["stamp"]] + + +@pytest.mark.parametrize("name", _names("text_cases")) +def test_text_cases(name: str, configure: Callable[[dict[str, Any]], Any]) -> None: + """The white space around a text - the 24 characters of the number rule and no other - and what it decides: + a setting's text loses it, and a required text of nothing else is missing, in both packs alike.""" + case = _case("text_cases", name) + assert configure({**BASE, aq.PAGE_TITLE: case["text"]}).page_title == case["trimmed"] + event = wait_event(summary=case["text"]) + if case["blank"]: + with pytest.raises(aq.AppException) as refused: + aq.validate_event(event) + assert (refused.value.status, refused.value.message) == (400, "summary is required") + else: + assert aq.validate_event(event)["summary"] == case["text"] + + +def test_the_white_space_of_a_number_and_of_a_text_is_the_same_24_characters() -> None: + """The white space around a number and the white space a blank text is made of are one set: no character of + the basic plane is the one and a character of a name, or the reverse.""" + event = wait_event() + + def blank(text: str) -> bool: + try: + aq.validate_event({**event, "summary": text}) + except aq.AppException: + return True + return False + + units = [chr(code) for code in range(0x10000)] + around_a_number = [ch for ch in units if aq.whole_number(f"{ch}5{ch}") == 5] + assert [ch for ch in units if blank(ch)] == around_a_number + assert len(around_a_number) == 24 + + +def _exact_rows(case: dict[str, Any]) -> list[Any]: + """The rows of an exact case as the database gives them - psycopg reads a BIGINT column as an int.""" + return [ + aq.row_from_record(_record( + id=int(s["id"]), seq=int(s["seq"]), kind=s["kind"], state=s["state"], correlation_id=f"case-{s['id']}", + ticket=None if s["kind"] == "advice" else f"t-{s['id']}", link=None)) + for s in case["rows"] + ] # fmt: skip + + +def _shown(page: dict[str, Any]) -> dict[str, Any]: + """A page as a query of an exact case names it: every number as text.""" + return {"ids": [str(r["id"]) for r in page["rows"]], "seqs": [str(r["seq"]) for r in page["rows"]], + "next": None if page["next"] is None else str(page["next"]), "more": page["more"]} + + +async def test_exact_cases_page_rows_by_the_numbers_they_have() -> None: + for case in VECTORS["exact_cases"]: + rows = _exact_rows(case) + reader = aq.MemoryReader() + for row in rows: + reader.put(row) + for query in case["queries"]: + if "before" in query: + before = None if query["before"] is None else int(query["before"]) + page = aq.page_before(rows, before, query["limit"]) + read = await reader.before(before, query["limit"]) + else: + page = aq.page_since(rows, int(query["since"]), query["limit"]) + read = await reader.since(int(query["since"]), query["limit"]) + assert _shown(page) == {k: query[k] for k in ("ids", "seqs", "next", "more")}, (case["name"], query) + assert [str(r.id) for r in read] == query["ids"], (case["name"], query) + assert str(await reader.latest()) == case["latest"] + + +def test_a_whole_float_is_the_whole_number_the_intake_answers_with() -> None: + """A turn written as a float with a whole value - all the Node.js twin sees of it - or in ASCII digits is the + whole number in the event the intake hands on, so both packs answer the same.""" + assert type(aq.validate_event(wait_event(turn=2.0))["turn"]) is int + assert type(aq.validate_event(wait_event(turn=" 2 "))["turn"]) is int + assert json.dumps(aq.validate_event(advice_event(turn=3.0))["turn"]) == "3" + assert "turn" not in aq.validate_event({k: v for k, v in advice_event().items() if k != "turn"}) + + # --- configuration and the fresh reader ------------------------------------------------------------ @@ -270,6 +432,43 @@ def apply(values: dict[str, Any]) -> Any: ({aq.AUTH: "oauth2"}, "set question.auth.oauth2.issuer or question.auth.oauth2.jwks-url"), ({aq.POSTGRES_PREFIX + "port": "db"}, "question.store.postgres.port must be a port number"), ({aq.POLL: "0"}, "question.poll must be a duration"), + # a switch is true or false: any other value stops the boot instead of being read as on + ({aq.POSTGRES_PREFIX + "ssl": "off"}, "question.store.postgres.ssl must be true or false"), + ({aq.POSTGRES_PREFIX + "ssl": "no"}, "question.store.postgres.ssl must be true or false"), + ({aq.POSTGRES_PREFIX + "ssl": 0}, "question.store.postgres.ssl must be true or false"), + # a number is ASCII digits: the digits of another script, a sign and a number past 2**53 - 1 are refused + ({aq.POSTGRES_PREFIX + "port": "\u0665\u0664\u0663\u0662"}, + "question.store.postgres.port must be a port number"), + ({aq.POSTGRES_PREFIX + "port": "+5432"}, "question.store.postgres.port must be a port number"), + ({aq.POSTGRES_PREFIX + "timeout.ms": "\uff15\uff10\uff10"}, + "question.store.postgres.timeout.ms must be a whole number of milliseconds > 0"), + ({aq.POSTGRES_PREFIX + "timeout.ms": 9007199254740992}, + "question.store.postgres.timeout.ms must be a whole number of milliseconds > 0"), + # a duration is such a number and, right after it, a unit + ({aq.POLL: "\u0663s"}, "question.poll must be a duration"), + ({aq.POLL: "1 s"}, "question.poll must be a duration"), + ({aq.REPLY_TIMEOUT: "1.5m"}, "question.reply.timeout must be a duration"), + ({aq.REPLY_TIMEOUT: "9007199254741s"}, "question.reply.timeout must be a duration"), + ({aq.POLL: "9" * 5000}, "question.poll must be a duration"), + # a setting that sets a timer takes no more than a timer holds in both packs: 2147483647 ms + ({aq.POLL: "2147483648ms"}, "question.poll must be a duration"), + ({aq.POLL: "25d"}, "question.poll must be a duration"), + ({aq.REPLY_TIMEOUT: 2147484}, "question.reply.timeout must be a duration"), + ({aq.POSTGRES_PREFIX + "timeout.ms": 2147483648}, + "question.store.postgres.timeout.ms must be a whole number of milliseconds > 0"), + # the host's keep-alive interval is how often a quiet stream looks for its device: the key's own message + ({"event.stream.keep.alive": "30d"}, + "event.stream.keep.alive must be a duration such as 30s, 2m or 500ms (seconds, ms, s, m, h, d), or 0 for none"), + ({"event.stream.keep.alive": "2147483648ms"}, + "event.stream.keep.alive must be a duration such as 30s, 2m or 500ms (seconds, ms, s, m, h, d), or 0 for none"), + # a port is 1 to 65535 + ({aq.POSTGRES_PREFIX + "port": 65536}, "question.store.postgres.port must be a port number"), + ({aq.POSTGRES_PREFIX + "port": "70000"}, "question.store.postgres.port must be a port number"), + ({aq.POSTGRES_PREFIX + "port": 0}, "question.store.postgres.port must be a port number"), + # a setting's text is trimmed by the white space of the number rule: any other character is part of it + ({aq.STORE: "\u0085memory"}, "question.store must be memory or postgres"), + ({aq.STORE: "memory\ufeff"}, "question.store must be memory or postgres"), + ({aq.AUTH: "\u001fnone"}, "question.auth must be one of none, oauth2"), ], ) def test_the_boot_fails_by_name(configure: Callable[[dict[str, Any]], Any], values: dict[str, Any], names: str) -> None: @@ -295,6 +494,73 @@ def test_the_postgres_settings_follow_the_audit_store(configure: Callable[[dict[ assert settings.oauth2_scopes == "openid profile email" +def test_settings_read_a_number_a_duration_and_a_switch_by_the_one_rule( + configure: Callable[[dict[str, Any]], Any] +) -> None: + """The text a ${NAME:default} reference resolves to and the value a YAML file holds are read alike: a switch in + any letter case, a whole number or a duration with white space around it, a float with a whole value.""" + settings = configure({ + **BASE, aq.POSTGRES_PREFIX + "ssl": "FALSE", aq.POSTGRES_PREFIX + "port": " 6543\n", + aq.POSTGRES_PREFIX + "timeout.ms": 2500.0, aq.POLL: " 007s ", aq.REPLY_TIMEOUT: 3.0, + }) # fmt: skip + assert settings.postgres["sslmode"] == "disable" + assert settings.postgres["port"] == 6543 + assert type(settings.postgres["port"]) is int + assert settings.postgres["options"] == "-c statement_timeout=2500" + assert settings.poll_ms == 7000 + assert settings.reply_timeout_ms == 3000 + on = configure({aq.POSTGRES_PREFIX + "ssl": "True"}) + assert on.postgres["sslmode"] == "require" + default = configure({aq.POSTGRES_PREFIX + "ssl": ""}) + assert default.postgres["sslmode"] == "require", "an empty value is the default" + + +def test_a_setting_that_sets_a_timer_takes_the_longest_wait_a_timer_holds( + configure: Callable[[dict[str, Any]], Any] +) -> None: + """2147483647 ms is the longest delay the Node.js twin's timers hold, so it is the most such a setting takes in + both packs - in any unit - the host's keep-alive among them; and a port is at most 65535.""" + settings = configure({ + **BASE, aq.POLL: "2147483647ms", aq.REPLY_TIMEOUT: "24d", aq.POSTGRES_PREFIX + "timeout.ms": "2147483647", + aq.POSTGRES_PREFIX + "port": 65535, "event.stream.keep.alive": "2147483s", + }) # fmt: skip + assert settings.poll_ms == 2_147_483_647 + assert settings.reply_timeout_ms == 2_073_600_000 + assert settings.postgres["options"] == "-c statement_timeout=2147483647" + assert settings.postgres["port"] == 65535 + assert configure({aq.POSTGRES_PREFIX + "port": "1"}).postgres["port"] == 1 + # a keep-alive that is no duration is the host's to refuse, by the same message, when it starts + assert configure({"event.stream.keep.alive": "soon"}).poll_ms == 2_147_483_647 + + +def test_a_quiet_stream_looks_for_its_device_at_the_keep_alive_a_timer_holds() -> None: + """At the host's keep-alive interval; every 30 seconds when the host sends none, and when the interval is + longer than a timer holds - where the Node.js twin's timer would fire at once, over and over.""" + assert aq.look_seconds(1000) == 1.0 + assert aq.look_seconds(500) == 0.5 + assert aq.look_seconds(2_147_483_647) == 2147483.647 + assert aq.look_seconds(0) == 30.0 + assert aq.look_seconds(2_147_483_648) == 30.0 + assert aq.look_seconds(2_592_000_000) == 30.0 + + +def test_a_setting_s_text_is_trimmed_by_the_white_space_of_the_number_rule( + configure: Callable[[dict[str, Any]], Any] +) -> None: + """A setting's text loses the 24 characters around it and no other, so both packs read the same value from one + file: a byte order mark, a next-line character or a separator - white space to one runtime's own trim only - is + part of it.""" + settings = configure({ + **BASE, aq.STORE: "\u00a0memory\u3000", aq.AUTH: "\u2028none\t", aq.PAGE_TITLE: "\u2003Questions\u205f", + aq.REPLY_TOKEN: "\ufefftoken\u0085", aq.OAUTH2_AUDIENCE: "\u001caudience\u001f", + }) # fmt: skip + assert settings.store == "memory" + assert settings.auth == "none" + assert settings.page_title == "Questions" + assert settings.reply_token == "\ufefftoken\u0085" + assert settings.oauth2_audience == "\u001caudience\u001f" + + # --- the intake and the feed ---------------------------------------------------------------------- @@ -458,6 +724,90 @@ async def test_the_replay_and_the_history_page_the_record(configure: Callable[[d assert (await get_json(f"{host}/questions?before=x"))[0] == 400 +async def test_the_list_reads_its_numbers_by_the_rule(configure: Callable[[dict[str, Any]], Any], host: str) -> None: + """since and before are numbers of the record, limit is a whole number: ASCII digits, or the 400 - the same + request gets the same answer from both packs.""" + configure(BASE) + seven_rows() + refusal = "since, before and limit must be whole numbers" + # another script's three, a sign, a fraction, a space, one past the largest number the record holds + for query in ("since=%D9%A3", "before=%D9%A3", "since=%2B3", "since=3.0", "since=%203", "before=3%20", + f"since={2**63}", f"before={2**63}", "limit=%D9%A3", "limit=%2B3", "limit=3.0", "limit=1%200", + f"limit={2**53}", "before=&limit=x"): + status, body = await get_json(f"{host}/questions?{query}") + assert status == 400, query + assert body["message"] == refusal, query + status, page = await get_json(f"{host}/questions?since=003&limit=%202%20") + assert status == 200 + assert [r["id"] for r in page["rows"]] == [4, 3], "leading zeros are digits; white space around a limit is ignored" + assert page["since"] == 3 + status, page = await get_json(f"{host}/questions?before={2**63 - 1}&limit={2**53 - 1}") + assert status == 200 + assert len(page["rows"]) == 7, "the largest cursor and the largest limit: every row, a page of the most it takes" + reader = aq.reader() + reader.put_conversation(conversation(CONVERSATION_A, "2026-11-19T09:00:00.000Z"), [turn(1)]) + reader.put_conversation(conversation(CONVERSATION_B, "2026-11-19T10:00:00.000Z"), [turn(1)]) + for query in ("limit=%D9%A1", "limit=%2B1", "limit=1.0", f"limit={2**53}"): + status, body = await get_json(f"{host}/transcripts?{query}") + assert status == 400, query + assert body["message"] == "limit must be a whole number", query + status, listed = await get_json(f"{host}/transcripts?limit=%2001%20") + assert status == 200 + assert [c["conversation"] for c in listed["conversations"]] == [CONVERSATION_B] + + +async def test_a_row_past_the_whole_numbers_a_double_holds_is_sent_with_every_digit( + configure: Callable[[dict[str, Any]], Any], host: str +) -> None: + """The record's id and seq are BIGINT columns: a page, a stream's event and a refusal tell a row by the + numbers it has - the Node.js twin's own numbers would round them, lose a row whose id rounds to another's and + put the page in another order.""" + configure(BASE) + case = VECTORS["exact_cases"][0] + for row in _exact_rows(case): + aq.reader().put(row) + async with aiohttp.ClientSession() as http: + for query in case["queries"]: + asked = f"before={query['before'] or ''}" if "before" in query else f"since={query['since']}" + async with http.get(f"{host}/questions?{asked}&limit={query['limit']}") as response: + assert response.status == 200, asked + page = json.loads(await response.text()) # Python reads every digit of a JSON number + assert _shown(page) == {k: query[k] for k in ("ids", "seqs", "next", "more")}, asked + async with http.get(f"{host}/questions/events", headers={"last-event-id": "9223372036854775806"}) as response: + first = (await asyncio.wait_for(response.content.readline(), 5)).decode() + second = (await asyncio.wait_for(response.content.readline(), 5)).decode() + assert first == "event: question\n" + sent = json.loads(second[len("data: "):]) + assert (str(sent["id"]), str(sent["seq"])) == ("9007199254740994", "9223372036854775807") + body = {"decisions": [{"id": "toolu_01A", "approved": True}]} + async with http.post(f"{host}/questions/9007199254740992/decide", json=body) as response: + assert response.status == 409 + assert (await response.json())["message"] == "row 9007199254740992 is an advice - nothing to decide" + async with http.post(f"{host}/questions/9007199254740995/decide", json=body) as response: + assert response.status == 404 + assert (await response.json())["message"] == "row 9007199254740995 is not in the record" + + +async def test_health_tells_a_cursor_past_the_whole_numbers_a_double_holds_in_its_digits( + configure: Callable[[dict[str, Any]], Any] +) -> None: + """The health reply is rendered by the host, and the Node.js twin's renders no number past 2**53 - 1: the + feed's cursor is a number up to there and its digits, as text, beyond - the same reply from both packs.""" + configure(BASE) + put(advice_event(), 1, 2**53 - 1) + await aq._feed.poll_once() + info = await aq.question_health({"type": "info"}, None) + assert info["feed"] == 9007199254740991 + assert type(info["feed"]) is int + for row in _exact_rows(VECTORS["exact_cases"][0]): + aq.reader().put(row) + await aq._feed.poll_once() + info = await aq.question_health({"type": "info"}, None) + assert info["feed"] == "9223372036854775807" + assert info["rows"] == {"advice": 2, "open": 2, "answered": 1, "expired": 1} + assert json.loads(json.dumps(info))["feed"] == "9223372036854775807", "the host's renderer takes the map" + + async def test_the_stream_replays_then_follows_the_feed_with_keep_alives( configure: Callable[[dict[str, Any]], Any], host: str ) -> None: @@ -631,6 +981,27 @@ async def recorder(body: dict[str, Any]) -> None: aq._wakeups.unsubscribe(queue) +async def test_a_whole_number_past_a_double_in_a_decision_and_in_a_row_is_sent_with_every_digit( + configure: Callable[[dict[str, Any]], Any], reply_endpoint: tuple[FakeReply, str] +) -> None: + """The click forwards the decisions and answers with the row: a whole number past 9007199254740991 goes to the + reply endpoint and to the invoker with every digit - the Node.js twin's own JSON refused such a number.""" + fake, base = reply_endpoint + configure({**BASE, aq.REPLY_TOKEN: "channel-app-bearer"}) + calls = [{"id": "toolu_01A", "name": "transfer_units", "route": "demo.units.transfer", "wait": True, + "input": {"units": 2**60 + 1}}] + row = put(wait_event(base=base, calls=calls), 1, 1) + request = (aq.AsyncHttpRequest().set_method("POST").set_url(f"/questions/{row.id}/decide") + .set_path_parameter("id", str(row.id)).set_body({"decisions": [{"id": "toolu_01A", "answer": 2**53 + 1}]})) + try: + answered = await aq.question_decide({}, request.to_map()) + finally: + await aq.shutdown() + assert answered.get_status() == 200 + assert fake.posts[-1]["body"]["decisions"] == [{"id": "toolu_01A", "answer": 9007199254740993}] + assert '"units": 1152921504606846977' in answered.body + + async def test_the_transcripts_are_browsed_from_the_audit_store( configure: Callable[[dict[str, Any]], Any], host: str ) -> None: @@ -663,6 +1034,16 @@ async def test_the_transcripts_are_browsed_from_the_audit_store( assert (await get_json(f"{host}/transcripts/{'f' * 32}"))[0] == 404 assert (await get_json(f"{host}/transcripts/not-a-conversation"))[0] == 400 assert (await get_json(f"{host}/transcripts?before=yesterday"))[0] == 400 + # before is a time by the one reader of both packs: at an offset it is the same instant - the plus sign of an + # offset is %2B in a URL, where a bare + is a space - and a time without an offset is none + status, at_an_offset = await get_json(f"{host}/transcripts?before=2026-11-19T12:00:00%2B01:00&limit=1") + assert status == 200 + assert [c["conversation"] for c in at_an_offset["conversations"]] == [CONVERSATION_B] + for text in ("2026-11-19T12:00:00+01:00", "2026-11-19T11:00:00", "2026-11-19T11:00:00z", "2026-11-19%2011:00:00Z", + "2026-11-19T11Z", "20261119T110000Z"): + status, refused = await get_json(f"{host}/transcripts?before={text}") + assert status == 400, text + assert refused["message"] == "before must be an ISO-8601 time", text assert (await get_json(f"{host}/transcripts?limit=x"))[0] == 400 @@ -697,6 +1078,12 @@ async def test_the_oauth2_mode_guards_every_read_and_the_click( async with http.get(f"{host}/questions?since=0", headers=bearer) as response: assert response.status == 200 assert [r["id"] for r in (await response.json())["rows"]] == [1] + # the token loses the white space of the number rule around it and no other: a next-line character is part + # of it in both packs, where this runtime's own trim took it off and let the token pass + async with http.get(f"{host}/questions?since=0", headers={"authorization": f"Bearer {token}\u00a0"}) as response: + assert response.status == 200 + async with http.get(f"{host}/questions?since=0", headers={"authorization": f"Bearer {token}\u0085"}) as response: + assert response.status == 401 async with http.get(f"{host}/transcripts", headers=bearer) as response: assert response.status == 200 async with http.post(f"{host}/questions/{row.id}/decide", json={"decisions": decisions, "decided_by": "spoof"}, diff --git a/tests/test_ask_person.py b/tests/test_ask_person.py index e5f8d22..189e761 100644 --- a/tests/test_ask_person.py +++ b/tests/test_ask_person.py @@ -4,7 +4,10 @@ expired and rotated; the message validated in its fixed order and the event built; the re-advice and the resume requests the reply page and endpoint send; the outcomes the invoker gets back; the row a message becomes in the question record, the state an answer leaves and the record's transitions on the reference -store. Then the function on the bus with channels that take, refuse and miss the event - the record +store; a payload's one spelling and the one rule for a number, a duration and a switch; a time read +by the one reader of both packs, the white space around a text, and whole numbers past the ones a +double holds written to the record with every digit. Then the +function on the bus with channels that take, refuse and miss the event - the record written before they are told - and the reply page and endpoint against a fake engine served in-process: the page's shell and the wait read without resuming, the decisions forwarded with who decided prefixed to each note and the answer recorded, an expired ticket refused before the engine is called, the two auth @@ -16,6 +19,11 @@ from __future__ import annotations +import asyncio +import base64 +import dataclasses +import hashlib +import hmac import importlib.util import json import os @@ -95,14 +103,31 @@ def _case(section: str, name: str) -> dict[str, Any]: return next(case for case in VECTORS[section] if case["name"] == name) +def _at(value: Any, place: list[Any]) -> Any: + """What stands at a place of a value: the keys and the indexes that lead to it.""" + for step in place: + value = value[step] + return value + + +def _placed(value: Any, numbers: list[dict[str, Any]]) -> Any: + """A copy of an exact case's value with each whole number at the place the case names - every digit, which + the vector file gives as text since a JSON number that large is not exact in every reader.""" + value = json.loads(json.dumps(value)) + for number in numbers: + _at(value, number["place"][:-1])[number["place"][-1]] = int(number["digits"]) + return value + + # --- the shared vectors --------------------------------------------------------------------------- def test_the_vector_file_is_the_shared_contract() -> None: assert VECTORS["contract"] == "ask-person" - assert VECTORS["version"] == 3 + assert VECTORS["version"] == 5 for section in ("ticket_cases", "verify_cases", "message_cases", "readvice_cases", "reply_cases", - "outcome_cases", "record_cases", "answer_cases", "transition_cases"): + "outcome_cases", "record_cases", "answer_cases", "transition_cases", "number_cases", + "switch_cases", "time_cases", "text_cases", "exact_cases"): assert VECTORS[section], section @@ -217,6 +242,73 @@ async def test_transition_cases_replay_on_the_reference_store() -> None: } +@pytest.mark.parametrize("name", _names("number_cases")) +def test_number_cases(name: str) -> None: + """A value read as a whole number and as a duration: the one rule of both packs and of every extension.""" + case = _case("number_cases", name) + assert ask.whole_number(case["value"]) == case["whole"] + assert ask.duration_ms(case["value"]) == case["duration_ms"] + + +@pytest.mark.parametrize("name", _names("switch_cases")) +def test_switch_cases(name: str) -> None: + """A switch: true or false, the default for no value and an empty one, and None - refused - for any other.""" + case = _case("switch_cases", name) + on, off = (True, False) if case["switch"] == "default" else (case["switch"], case["switch"]) + assert ask.switch_value(case["value"], True) is on + assert ask.switch_value(case["value"], False) is off + + +_EPOCH = datetime(1970, 1, 1, tzinfo=UTC) + + +@pytest.mark.parametrize("name", _names("time_cases")) +def test_time_cases(name: str) -> None: + """A time a caller supplies, by the one reader of both packs: the instant to the millisecond and the text + written back for it - or no time at all, and a stamp the store gave as text is then kept as it came.""" + case = _case("time_cases", name) + moment = ask.parse_iso(case["text"]) + if case["ms"] is None: + assert moment is None + assert ask._stamp(case["text"]) == case["text"] + else: + assert (moment - _EPOCH) // timedelta(milliseconds=1) == case["ms"] + assert ask._stamp(case["text"]) == case["stamp"] + + +@pytest.mark.parametrize("name", _names("text_cases")) +def test_text_cases(name: str, configure: Callable[[dict[str, Any]], Any]) -> None: + """The white space around a text - the 24 characters of the number rule and no other - and what it decides: + a setting's text loses it, and a required text of nothing else is missing, in both packs alike.""" + case = _case("text_cases", name) + assert configure({**BASE, ask.OAUTH2_AUDIENCE: case["text"]}).oauth2_audience == case["trimmed"] + message = approval_message(summary=case["text"], requested_at="2026-11-19T09:12:04.118Z") + if case["blank"]: + with pytest.raises(ask.AppException) as refused: + ask.validate_message(message) + assert (refused.value.status, refused.value.message) == (400, "summary is required") + else: + assert ask.validate_message(message).summary == case["text"] + + +def test_the_white_space_of_a_number_and_of_a_text_is_the_same_24_characters() -> None: + """The white space around a number and the white space a blank text is made of are one set: no character of + the basic plane is the one and a character of a name, or the reverse.""" + message = approval_message(requested_at="2026-11-19T09:12:04.118Z") + + def blank(text: str) -> bool: + try: + ask.validate_message({**message, "summary": text}) + except ask.AppException: + return True + return False + + units = [chr(code) for code in range(0x10000)] + around_a_number = [ch for ch in units if ask.whole_number(f"{ch}5{ch}") == 5] + assert [ch for ch in units if blank(ch)] == around_a_number + assert len(around_a_number) == 24 + + def test_the_duration_grammar() -> None: assert ask.duration_ms("500ms") == 500 assert ask.duration_ms("30m") == 1_800_000 @@ -241,6 +333,40 @@ def test_requested_at_defaults_to_now_and_the_expiry_follows_the_ttl() -> None: assert event["link"] == f"{REPLY_URL}/ask/{event['ticket']}" +def test_a_wait_ends_before_the_year_10000_whenever_it_was_requested() -> None: + """requested_at is now when the message names none: a ttl that carries now past the year 9999 is the 400 a + requested_at of that year gets - where the expiry was an OverflowError no caller could read - and a message + that was never validated is refused the same way when its event is built.""" + with pytest.raises(ask.AppException) as refused: + ask.validate_message(approval_message(ttl="2913000d")) + assert (refused.value.status, refused.value.message) == (400, "ttl must end before the year 10000") + message = ask.validate_message(approval_message(ttl="2800000d")) + event = ask.build_event(message, KEY.encode(), REPLY_URL) + assert ask.parse_iso(event["expires_at"]) - ask.parse_iso(event["requested_at"]) == timedelta(days=2_800_000) + with pytest.raises(ask.AppException) as unchecked: + ask.build_event(dataclasses.replace(message, ttl_ms=ask.MAX_WHOLE), KEY.encode(), REPLY_URL) + assert (unchecked.value.status, unchecked.value.message) == (400, "ttl must end before the year 10000") + + +def test_an_expiry_before_1970_is_its_whole_seconds_below() -> None: + """The expiry a ticket carries is the floor of its seconds: a quarter of a second before 1970 is -1, as the + Node.js twin counts it, where cutting the fraction off gave 0 and the two packs issued different tickets.""" + message = ask.validate_message(approval_message(requested_at="1969-12-31T23:59:58.250Z", ttl=1)) + event = ask.build_event(message, KEY.encode(), REPLY_URL) + assert event["expires_at"] == "1969-12-31T23:59:59.250Z" + assert ask.verify_ticket(event["ticket"], [KEY.encode()], -10)["e"] == -1 + + +def test_a_whole_float_is_the_whole_number_in_the_event() -> None: + """A turn and a ttl written as floats with a whole value - all the Node.js twin sees of them - leave the + message as the whole numbers they are, so both packs send the same event.""" + event = ask.build_event(ask.validate_message(approval_message(turn=2.0, ttl=3600.0)), KEY.encode(), REPLY_URL) + assert type(event["turn"]) is int + assert type(event["ttl"]) is int + assert json.dumps({"turn": event["turn"], "ttl": event["ttl"]}) == '{"turn": 2, "ttl": 3600}' + assert ask.verify_ticket(event["ticket"], [KEY.encode()], 0)["t"] == 2 + + _BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" @@ -277,6 +403,43 @@ def test_a_ticket_has_one_spelling() -> None: assert lengths == {0, 2, 3} +def _signed(payload: bytes) -> str: + """A ticket whose payload part is these bytes, signed with the current key: what a key holder can make.""" + def part(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + return f"v1.{part(payload)}.{part(hmac.new(KEY.encode(), payload, hashlib.sha256).digest())}" + + +def test_a_signed_payload_has_one_spelling() -> None: + """The payload under a valid signature is the canonical JSON of a wait's five fields: the issuer's own bytes + verify, and the same wait spelled another way - or nested deeper than the decoder reads - is malformed.""" + now = 1795089600 + payload = {"g": "order-assistant", "c": "order-1002-case", "t": 2, "k": "approval", "e": now + 3600} + canonical = ask.canonical_json(payload).encode("utf-8") + keys = [KEY.encode()] + assert ask.verify_ticket(_signed(canonical), keys, now) == payload + others = [ + canonical.replace(b'"t":2', b'"t":2.0'), + canonical.replace(b'"t":2', b'"t":-0'), + canonical.replace(b'"t":2', b'"t":9007199254740992'), + canonical.replace(b"order-1002", b"order-\\u0031002"), + canonical.replace(b"order-1002", b"order-\\ud800"), + canonical.replace(b"order-1002", b"order-\xff"), + canonical.replace(b'"t":2', b'"t":2,"t":2'), + canonical.replace(b",", b", "), + json.dumps(payload, separators=(",", ":")).encode("utf-8"), + canonical + b"\n", + canonical.replace(b'"t":2', b'"t":' + b"9" * 5000), + b"[" * 100_000 + b"]" * 100_000, + ] + for other in others: + ticket = _signed(other) + with pytest.raises(ask.TicketError) as refused: + ask.verify_ticket(ticket, keys, now) + assert (refused.value.status, refused.value.message) == (400, "Ticket is malformed"), other[:80] + + # --- configuration ---------------------------------------------------------------------------------- @@ -349,6 +512,45 @@ def test_settings_read_lists_and_pairs_in_both_forms(configure: Callable[[dict[s ({ask.GRAPHS: [{"id": "g"}]}, "ask.graphs entries need id and entry"), ({ask.CHANNEL_ENDPOINTS: "nonsense"}, "ask.channel.endpoints takes route=url pairs"), ({ask.CHANNEL_TIMEOUT: "0"}, "ask.channel.timeout must be a duration"), + # a switch is true or false: any other value stops the boot instead of leaving the switch off + ({ask.ENABLED: "maybe"}, "ask.enabled must be true or false"), + ({ask.ENABLED: "yes"}, "ask.enabled must be true or false"), + ({ask.ENABLED: 1}, "ask.enabled must be true or false"), + ({ask.AUDIT_POSTGRES_PREFIX + "ssl": "off"}, "ask.audit.postgres.ssl must be true or false"), + ({ask.AUDIT_POSTGRES_PREFIX + "ssl": " false"}, "ask.audit.postgres.ssl must be true or false"), + # a number is ASCII digits: the digits of another script, a sign and a number past 2**53 - 1 are refused + ({ask.AUDIT_INSTANCES: "\u0663"}, "ask.audit.instances must be a whole number >= 1"), + ({ask.AUDIT_INSTANCES: "+3"}, "ask.audit.instances must be a whole number >= 1"), + ({ask.AUDIT_INSTANCES: 9007199254740992}, "ask.audit.instances must be a whole number >= 1"), + ({ask.AUDIT_POSTGRES_PREFIX + "timeout.ms": "\uff15\uff10\uff10"}, + "ask.audit.postgres.timeout.ms must be a whole number >= 1"), + ({ask.AUDIT_POSTGRES_PREFIX + "port": "\u0665\u0664\u0663\u0662"}, + "ask.audit.postgres.port must be a port number"), + ({ask.AUDIT_POSTGRES_PREFIX + "port": 5432.5}, "ask.audit.postgres.port must be a port number"), + # a duration is such a number and, right after it, a unit + ({ask.CHANNEL_TIMEOUT: "\u0663s"}, "ask.channel.timeout must be a duration"), + ({ask.CHANNEL_TIMEOUT: "2 s"}, "ask.channel.timeout must be a duration"), + ({ask.ENGINE_TIMEOUT: "1.5m"}, "ask.engine.timeout must be a duration"), + ({ask.AUDIT_SWEEP: "9007199254741s"}, "ask.audit.sweep must be a duration"), + ({ask.AUDIT_TIMEOUT: "9" * 5000}, "ask.audit.timeout must be a duration"), + # a setting that sets a timer takes no more than a timer holds in both packs: 2147483647 ms + ({ask.CHANNEL_TIMEOUT: "2147483648ms"}, "ask.channel.timeout must be a duration"), + ({ask.ENGINE_TIMEOUT: "25d"}, "ask.engine.timeout must be a duration"), + ({ask.AUDIT_SWEEP: "30d"}, "ask.audit.sweep must be a duration"), + ({ask.AUDIT_TIMEOUT: 2147484}, "ask.audit.timeout must be a duration"), + ({ask.AUDIT_POSTGRES_PREFIX + "timeout.ms": 2147483648}, + "ask.audit.postgres.timeout.ms must be a whole number >= 1"), + ({ask.AUDIT_POSTGRES_PREFIX + "timeout.ms": "9007199254740991"}, + "ask.audit.postgres.timeout.ms must be a whole number >= 1"), + # a port is 1 to 65535 + ({ask.AUDIT_POSTGRES_PREFIX + "port": 65536}, "ask.audit.postgres.port must be a port number"), + ({ask.AUDIT_POSTGRES_PREFIX + "port": "70000"}, "ask.audit.postgres.port must be a port number"), + ({ask.AUDIT_POSTGRES_PREFIX + "port": 0}, "ask.audit.postgres.port must be a port number"), + # a setting's text is trimmed by the white space of the number rule: any other character is part of it + ({ask.REPLY_AUTH: "\u0085none"}, "ask.reply.auth must be one of none, oauth2"), + ({ask.REPLY_AUTH: "none\ufeff"}, "ask.reply.auth must be one of none, oauth2"), + ({ask.AUDIT: "\u001fmemory"}, "ask.audit must be one of memory, postgres"), + ({ask.REPLY_URL: "\ufeffhttps://ask.example.test"}, "ask.reply.url must be the public base"), ], ) def test_the_boot_fails_by_name( @@ -365,6 +567,108 @@ def test_a_disabled_extension_loads_without_a_key(configure: Callable[[dict[str, assert settings.keys == () +def test_settings_read_a_number_a_duration_and_a_switch_by_the_one_rule( + configure: Callable[[dict[str, Any]], Any] +) -> None: + """The text a ${NAME:default} reference resolves to and the value a YAML file holds are read alike: a switch in + any letter case, a whole number or a duration with white space around it, a float with a whole value.""" + settings = configure({ + **BASE, ask.ENABLED: "TRUE", ask.CHANNEL_TIMEOUT: " 1500ms ", ask.ENGINE_TIMEOUT: 90.0, ask.AUDIT_SWEEP: "007s", + ask.AUDIT_TIMEOUT: "2", ask.AUDIT_INSTANCES: " 3\n", ask.AUDIT_POSTGRES_PREFIX + "ssl": "False", + ask.AUDIT_POSTGRES_PREFIX + "port": " 6543 ", ask.AUDIT_POSTGRES_PREFIX + "timeout.ms": 2500.0, + }) # fmt: skip + assert settings.enabled is True + assert settings.channel_timeout_ms == 1500 + assert settings.engine_timeout_ms == 90_000 + assert settings.audit_sweep_ms == 7000 + assert settings.audit_timeout_ms == 2000 + assert settings.audit_instances == 3 + assert settings.audit_postgres["sslmode"] == "disable" + assert settings.audit_postgres["port"] == 6543 + assert type(settings.audit_postgres["port"]) is int + assert settings.audit_postgres["options"] == "-c statement_timeout=2500" + off = configure({ask.ENABLED: "false", ask.AUDIT_POSTGRES_PREFIX + "ssl": ""}) + assert off.enabled is False + assert off.audit_postgres["sslmode"] == "require", "an empty value is the default" + + +def test_a_setting_that_sets_a_timer_takes_the_longest_wait_a_timer_holds( + configure: Callable[[dict[str, Any]], Any] +) -> None: + """2147483647 ms is the longest delay the Node.js twin's timers hold, so it is the most such a setting takes in + both packs - in any unit - and a port is at most 65535.""" + settings = configure({ + **BASE, ask.CHANNEL_TIMEOUT: "2147483647ms", ask.ENGINE_TIMEOUT: "2147483s", ask.AUDIT_SWEEP: "24d", + ask.AUDIT_TIMEOUT: 2147483, ask.AUDIT_POSTGRES_PREFIX + "timeout.ms": "2147483647", + ask.AUDIT_POSTGRES_PREFIX + "port": 65535, + }) # fmt: skip + assert settings.channel_timeout_ms == 2_147_483_647 + assert settings.engine_timeout_ms == 2_147_483_000 + assert settings.audit_sweep_ms == 2_073_600_000 + assert settings.audit_timeout_ms == 2_147_483_000 + assert settings.audit_postgres["options"] == "-c statement_timeout=2147483647" + assert settings.audit_postgres["port"] == 65535 + assert configure({ask.AUDIT_POSTGRES_PREFIX + "port": "1"}).audit_postgres["port"] == 1 + + +def test_a_setting_s_text_is_trimmed_by_the_white_space_of_the_number_rule( + configure: Callable[[dict[str, Any]], Any] +) -> None: + """A setting's text loses the 24 characters around it and no other, so both packs read one key, one list of + names and one mode from the same file: a byte order mark, a next-line character or a separator - white space + to one runtime's own trim only - is part of the value.""" + settings = configure({ + **BASE, ask.TICKET_KEY: "\u00a0key\u3000", ask.PREVIOUS_KEY: "\ufeffold\u0085", ask.REPLY_AUTH: "\u2028none\t", + ask.CHANNELS: "a.route\u0085,\u2003b.route\u00a0, \ufeff ,\u001f", ask.OAUTH2_AUDIENCE: "\u001caudience\ufeff", + ask.GRAPHS: "\u205fg1\u1680=\u2000http://e/1\u200a, g\u0085=http://e/2\ufeff", + ask.CHANNEL_ENDPOINTS: [{"route": "\tb.route\u2029", "url": "\u202fhttp://peer/api/event\n"}], + }) # fmt: skip + assert settings.keys == (b"key", "\ufeffold\u0085".encode()) + assert settings.auth == "none" + assert settings.channels == ("a.route\u0085", "b.route", "\ufeff", "\u001f") + assert settings.oauth2_audience == "\u001caudience\ufeff" + assert settings.graphs == {"g1": "http://e/1", "g\u0085": "http://e/2\ufeff"} + assert settings.channel_endpoints == {"b.route": "http://peer/api/event"} + + +def test_a_graph_and_a_route_may_carry_the_name_of_a_member_every_object_has( + configure: Callable[[dict[str, Any]], Any] +) -> None: + """The allowlist and the endpoints are tables of the names the configuration gives, whatever they are - the + Node.js twin keeps them as an object's own keys, where a plain lookup would find constructor and lose + __proto__.""" + settings = configure({ + **BASE, + ask.GRAPHS: [{"id": "__proto__", "entry": "http://e/p"}, {"id": "constructor", "entry": "http://e/c"}], + ask.CHANNEL_ENDPOINTS: "__proto__=http://peer/api/event, toString=http://other/api/event", + }) + assert settings.graphs == {"__proto__": "http://e/p", "constructor": "http://e/c"} + assert settings.channel_endpoints == {"__proto__": "http://peer/api/event", "toString": "http://other/api/event"} + payload = {"g": "__proto__", "c": "order-1002-case", "t": 2, "k": "approval", "e": 1795252324} + graphs = settings.graphs + assert ask.readvice_request(payload, graphs).url == "http://e/p" + other = {**payload, "g": "toString"} + with pytest.raises(ask.ReplyError) as refused: + ask.readvice_request(other, graphs) + assert (refused.value.status, refused.value.message) == (404, "graph toString is not configured for replies") + + +async def test_a_channel_named_as_a_member_every_object_has_is_a_route_nobody_serves( + configure: Callable[[dict[str, Any]], Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """A channel has an endpoint only when the configuration gives it one: a route named constructor or + __proto__ with none is looked for in this process and, as nobody serves it, reported as any missing route.""" + settings = configure({**BASE, ask.CHANNELS: ["constructor", "__proto__", "ask.test.nobody"]}) + registry = FunctionRegistry() + monkeypatch.setattr(ask, "_post_office", PostOffice(registry=registry)) + event = ask.build_event(ask.validate_message(approval_message()), KEY.encode(), REPLY_URL) + try: + delivered = await ask.deliver(event, settings) + finally: + await registry.bus.close() + assert delivered == [{"route": route, "ok": False, "status": 404} for route in settings.channels] + + # --- the function on the bus ----------------------------------------------------------------------- @@ -567,6 +871,8 @@ async def graph(self, request: web.Request) -> web.Response: body = await request.json() cid = request.headers.get("x-correlation-id") self.requests.append({"graph": request.match_info["graph_id"], "cid": cid, "body": body}) + if cid == "slow-case": + await asyncio.sleep(0.1) # an engine that takes its time if cid == "expired-case": return web.json_response({"type": "nothing-waiting", "cid": cid}, status=410) if "decisions" in body: @@ -704,6 +1010,30 @@ async def test_the_page_refuses_bad_tickets_and_reports_an_expired_wait( assert len(fake.requests) == 1 +async def test_a_graph_named_as_a_member_every_object_has_is_not_configured( + configure: Callable[[dict[str, Any]], Any], engine: tuple[FakeEngine, str], host: str +) -> None: + """A graph id from a ticket matches the names the allowlist gives and no other: constructor, toString and + __proto__ are members every object of the Node.js twin has, and none of them is a graph.""" + fake, engine_url = engine + configure({**BASE, ask.GRAPHS: f"order-assistant={engine_url}/api/graph/order-assistant"}) + decisions = [{"id": "toolu_01A", "approved": True}] + async with aiohttp.ClientSession() as http: + for graph_id in ("constructor", "toString", "hasOwnProperty", "__proto__"): + ticket = _ticket(graph_id=graph_id) + refusal = f"graph {graph_id} is not configured for replies" + async with http.get(f"{host}/ask/{ticket}") as response: + assert response.status == 404, graph_id + assert refusal in await response.text(), graph_id + async with http.get(f"{host}/ask/{ticket}/wait") as response: + assert response.status == 404, graph_id + assert (await response.json())["message"] == refusal, graph_id + async with http.post(f"{host}/ask/reply", json={"ticket": ticket, "decisions": decisions}) as response: + assert response.status == 404, graph_id + assert (await response.json())["message"] == refusal, graph_id + assert fake.requests == [], "no ticket above reached the engine" + + async def test_a_reply_resumes_the_graph_with_who_decided_on_each_note( configure: Callable[[dict[str, Any]], Any], engine: tuple[FakeEngine, str], host: str ) -> None: @@ -871,6 +1201,42 @@ async def test_the_oauth2_mode_validates_an_access_token_and_the_page_learns_how assert fake.requests[-1]["body"]["decisions"][0]["note"].startswith("[operator-9 at ") +async def test_a_bearer_is_trimmed_by_the_white_space_of_the_number_rule( + configure: Callable[[dict[str, Any]], Any] +) -> None: + """The token after Bearer loses the 24 characters around it and no other, and is compared as its bytes: a + next-line character, a separator or a byte order mark is part of the token in both packs - one runtime's own + trim took it off and let the token pass, and a character past ASCII was an error no caller could read.""" + settings = configure({**BASE, ask.APP_TOKEN: APP_TOKEN}) + + async def via(header: str) -> str: + request = ask.AsyncHttpRequest().set_header("authorization", header) + return (await ask.identify(request, settings, "operator-9", True)).via + + assert await via(f"Bearer {APP_TOKEN}") == "app" + assert await via(f"Bearer \u00a0{APP_TOKEN}\u3000") == "app" + assert await via(f"Bearer {APP_TOKEN}\u0085") == "none" + assert await via(f"Bearer {APP_TOKEN}\u001f") == "none" + assert await via(f"Bearer {APP_TOKEN}\ufeff") == "none" + assert await via("Bearer caf\u00e9") == "none" + assert await via("Bearer \u2003") == "none" + + +async def test_the_engine_has_its_time_at_the_longest_wait_a_timer_holds( + configure: Callable[[dict[str, Any]], Any], engine: tuple[FakeEngine, str], host: str +) -> None: + """ask.engine.timeout at the most a timer holds: the request to the engine is given that long and no longer - + a second more would carry the Node.js twin's timer past what it holds, which aborts the request at once, before + a graph that takes a tenth of a second has answered.""" + _fake, engine_url = engine + configure({**BASE, ask.GRAPHS: f"order-assistant={engine_url}/api/graph/order-assistant", + ask.ENGINE_TIMEOUT: "2147483647ms"}) + body = {"ticket": _ticket(cid="slow-case"), "decisions": [{"id": "toolu_01A", "approved": True}]} + async with aiohttp.ClientSession() as http, http.post(f"{host}/ask/reply", json=body) as response: + assert response.status == 200 + assert (await response.json())["type"] == "answer" + + # --- the PostgreSQL store on a recording fake of the pool ----------------------------------------- @@ -993,6 +1359,94 @@ async def test_the_postgres_store_runs_the_statements_and_maps_the_records() -> assert ask.failure(RuntimeError("quotes a row")) == "RuntimeError" +async def test_a_row_past_the_whole_numbers_a_double_holds_is_told_by_the_number_it_has( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The record's id and seq are BIGINT columns: a row is told by the numbers it has - in the row, in the + recorder's answer and in its log line - where the Node.js twin's own numbers would round them.""" + largest, past = 2**63 - 1, 2**53 + 1 + row = ask.row_from_record(_record(id=largest, seq=past)) + assert (str(row.id), str(row.seq)) == ("9223372036854775807", "9007199254740993") + monkeypatch.setattr(ask, "_store", ask.PostgresQuestionStore(_FakePool([_record(id=largest, seq=past)]), 2.5)) + event = ask.build_event(ask.validate_message(approval_message()), KEY.encode(), REPLY_URL) + with caplog.at_level("INFO"): + answer = await ask.question_audit({}, {"record": event}) + assert {name: str(value) for name, value in answer.items()} == { + "recorded": "True", "id": "9223372036854775807", "seq": "9007199254740993", "state": "open"} + assert "recorded approval 9223372036854775807 for order-assistant turn 2 (seq 9007199254740993)" in caplog.text + + +async def test_exact_cases_reach_the_record_with_every_digit(monkeypatch: pytest.MonkeyPatch) -> None: + """A whole number past 9007199254740991 in a waiting call's input, and in a decision: the record's message and + decisions columns are given the text both packs write, every digit in it - the Node.js twin's own JSON refused + such a number, and its question was not recorded.""" + for case in VECTORS["exact_cases"]: + event = ask.build_event(ask.validate_message(_placed(case["message"], case["numbers"])), + case["key"].encode(), case["reply_url"]) + assert event["ticket"] == case["ticket"] + pool = _FakePool([_record()]) + monkeypatch.setattr(ask, "_store", ask.PostgresQuestionStore(pool, 2.5)) + recorded = await ask.question_audit({}, {"record": event}) + assert recorded["recorded"] is True, case["name"] + params = pool.log[-1][1] + assert params is not None + assert params[7] == case["record"], case["name"] + answer = {"graph_id": event["graph_id"], "correlation_id": event["correlation_id"], "turn": event["turn"], + "decisions": _placed(case["decisions"], case["decision_numbers"]), "who": "operator-9", "status": 200, + "body": {"type": "answer"}} + answered = await ask.question_audit({}, {"answer": answer}) + assert answered["recorded"] is True, case["name"] + params = pool.log[-1][1] + assert params is not None + assert params[1] == case["decisions_record"], case["name"] + + +async def test_a_whole_number_past_a_double_crosses_the_bus_to_the_channels_and_the_record( + configure: Callable[[dict[str, Any]], Any], channel: list[dict[str, Any]], recorder: Any +) -> None: + """The same message through the function: the channel is handed every number as it was sent, and the row the + recorder keeps is the event the channel got.""" + case = VECTORS["exact_cases"][0] + configure({**BASE, ask.CHANNELS: ["ask.test.channel"]}) + office = PostOffice(registry=default_registry) + reply = await office.request(ask.ROUTE, _placed(case["message"], case["numbers"]), timeout_ms=5000) + assert reply.get_status() == 200, reply.body + assert reply.body["recorded"] is True + assert reply.body["delivered"] == [{"route": "ask.test.channel", "ok": True, "status": 200}] + assert reply.body["ticket"] == case["ticket"] + assert reply.body["expires_at"] == case["expires_at"] + for number in case["numbers"]: + assert str(_at(channel[0], number["place"])) == number["digits"], number["place"] + rows = await recorder.since(0, 10) + assert json.dumps(rows[0].message, separators=(",", ":"), ensure_ascii=False) == case["record"] + + +async def test_a_whole_number_past_a_double_in_a_decision_reaches_the_engine_and_the_record( + configure: Callable[[dict[str, Any]], Any], engine: tuple[FakeEngine, str], recorder: Any +) -> None: + """A decision that carries such a number: the resume the engine receives and the answer on the row hold every + digit of it.""" + case = VECTORS["exact_cases"][0] + fake, engine_url = engine + configure({**BASE, ask.GRAPHS: f"ledger-assistant={engine_url}/api/graph/ledger-assistant"}) + event = ask.build_event(ask.validate_message(_placed(case["message"], case["numbers"])), KEY.encode(), REPLY_URL) + await recorder.record(event, ask.iso_utc()) + decisions = _placed(case["decisions"], case["decision_numbers"]) + ticket = _ticket(graph_id=event["graph_id"], cid=event["correlation_id"], turn=event["turn"]) + request = ask.AsyncHttpRequest().set_method("POST").set_url("/ask/reply").set_body({"ticket": ticket, "decisions": decisions}) + try: + reply = await ask.ask_reply({}, request.to_map()) + finally: + await ask.shutdown() + assert reply.get_status() == 200, reply.body + for number in case["decision_numbers"]: + assert str(_at(fake.requests[-1]["body"]["decisions"], number["place"])) == number["digits"] + rows = await recorder.since(0, 10) + assert rows[0].state == "answered" + for number in case["decision_numbers"]: + assert str(_at(rows[0].decisions, number["place"])) == number["digits"] + + async def test_the_boot_registers_the_recorder_and_a_silent_database_does_not_stop_it( configure: Callable[[dict[str, Any]], Any], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, diff --git a/tests/vectors/agent-question-vectors.json b/tests/vectors/agent-question-vectors.json index 6196d47..365a5b4 100644 --- a/tests/vectors/agent-question-vectors.json +++ b/tests/vectors/agent-question-vectors.json @@ -1,7 +1,7 @@ { "contract": "agent-question", - "version": 4, - "description": "The agent-question app's shared vectors (RFC-0014, build plan steps 3 and 10): the pure half of extensions/agent-question, run by mercury-python and mercury-nodejs against the same file. Version 3 (round 4): the app reads the question record the main flow keeps and writes nothing - the row a message becomes, the state an answer leaves and the record's transitions moved to the ask-person vectors (version 2). intake_cases pin the event the intake accepts (what it answers the main flow) or the exact 400 that refuses it. click_cases pin the request the automated click sends to the reply endpoint the link names. feed_cases pin the pages the replay and the history read over a fixed set of rows: since(seq, limit) - the rows whose sequence passed the cursor, oldest first, with the cursor to continue from - and before(seq, limit) - the rows before the cursor, newest first, with the cursor of the older page (every row when the cursor is null); more says a page was full. Version 4 (the numbers a request names): row_id_cases pin the row a decision names in /questions/{id}/decide, and cursor_cases where a device's stream starts - its Last-Event-ID, else its since parameter, else the beginning. Each is one to nineteen ASCII digits from start to end and no larger than 9223372036854775807, the largest number the record's BIGINT id and seq columns hold; anything else is the exact 400. The number read is given as text, since a JSON number past 2^53 is not exact in every reader.", + "version": 6, + "description": "The agent-question app's shared vectors (RFC-0014, build plan steps 3 and 10): the pure half of extensions/agent-question, run by mercury-python and mercury-nodejs against the same file. Version 3 (round 4): the app reads the question record the main flow keeps and writes nothing - the row a message becomes, the state an answer leaves and the record's transitions moved to the ask-person vectors (version 2). intake_cases pin the event the intake accepts (what it answers the main flow) or the exact 400 that refuses it. click_cases pin the request the automated click sends to the reply endpoint the link names. feed_cases pin the pages the replay and the history read over a fixed set of rows: since(seq, limit) - the rows whose sequence passed the cursor, oldest first, with the cursor to continue from - and before(seq, limit) - the rows before the cursor, newest first, with the cursor of the older page (every row when the cursor is null); more says a page was full. Version 4 (the numbers a request names): row_id_cases pin the row a decision names in /questions/{id}/decide, and cursor_cases where a device's stream starts - its Last-Event-ID, else its since parameter, else the beginning. Each is one to nineteen ASCII digits from start to end and no larger than 9223372036854775807, the largest number the record's BIGINT id and seq columns hold; anything else is the exact 400. The number read is given as text, since a JSON number past 2^53 is not exact in every reader. Version 5 (one rule for a number, a duration and a switch; a row told by the number it has). number_cases and switch_cases are the ask-person vectors' (version 4), read by this app's own readers: a whole number, a duration in milliseconds, a switch. intake_cases gain a turn in each spelling the rule reads - the answer carries the whole number - and in spellings it refuses. list_cases pin what GET /questions asks for, from its parameters as the request wrote them: whether it pages back (before is named, though empty), the cursor - since and before are numbers of the record, read as a row id is, digits from start to end - and the page size, a whole number held between 1 and 1000; or the exact 400. page_size_cases pin a page size against a default and a most, as the transcripts' limit is read. exact_cases pin rows whose id and sequence are past 9007199254740991, with every id, sequence and cursor given as text, since a JSON number that large is not exact in every reader: the rows as the database holds them and the queries as feed_cases have them; a page holds the rows by the numbers they have, in their order, with the cursor to continue from, and what a client is sent carries every digit. Version 6 (one reader of a time; a turn the record holds; blank by one rule). time_cases and text_cases are the ask-person vectors' (version 5), read by this app's own readers: a time a caller supplies - the transcripts' before, an event's requested_at and expires_at - as the instant in milliseconds from 1970-01-01T00:00:00Z and the text both packs write for it, or null where the text is no time; and the white space around a text, the 24 characters of the number rule. intake_cases gain a requested_at and an expires_at in the spellings the rule reads and in spellings it refuses, the exact 400; a turn up to 2147483647, the largest the record's INTEGER column holds, and the 400 past it (the largest turn of version 5 was 9007199254740991); required texts that are blank, and texts of characters that are not white space.", "intake_cases": [ { "name": "an approval", @@ -408,815 +408,5940 @@ }, "status": 400, "error": "details must be text" + }, + { + "name": "a turn written as a float with a whole value is that turn", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2.0, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a turn written in ASCII digits is that turn", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a turn with white space around its digits", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "\t2 ", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a turn of zero", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 0, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 0 + } + }, + { + "name": "the largest turn", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483647, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2147483647 + } + }, + { + "name": "an advice's turn written in ASCII digits", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "3", + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "accepted": { + "accepted": true, + "kind": "advice", + "graph_id": "order-assistant", + "turn": 3 + } + }, + { + "name": "a turn one past the largest", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483648, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a negative turn", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": -1, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a fraction", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2.5, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn in Arabic-Indic digits", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "٢", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a plus sign", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "+2", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a point in text", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2.0", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of empty text", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "an advice's turn with a fraction", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3.5, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a requested_at at an offset", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:12:04.118+01:00", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a requested_at to the minute", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a requested_at with a fraction of nine digits", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118999999Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "an expires_at at an offset", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T10:12:04.118+01:00", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "an expires_at in the last second of the year 9999", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "9999-12-31T23:59:59.999Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "an advice's requested_at at an offset", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T10:40:12.004+01:00" + }, + "accepted": { + "accepted": true, + "kind": "advice", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "an advice with an expires_at that is no time: an advice has no expiry, and none is read", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z", + "expires_at": "never" + }, + "accepted": { + "accepted": true, + "kind": "advice", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a requested_at that is a word", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "yesterday", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at without an offset", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at with a lower-case z", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at with a space for the T", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19 09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at with white space around it", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": " 2026-11-19T09:12:04.118Z\n", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at on the 30th of February", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-02-30T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at to the hour", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at of empty text", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "an advice's requested_at in the basic format", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "20261119T094012Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at that is a number is not text", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": 1795079524, + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be text" + }, + { + "name": "an expires_at that is a word", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "tomorrow", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at without an offset", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at with a lower-case t", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21t09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at at hour 24", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T24:00:00Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at in the year 10000", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "10000-01-01T00:00:00.000Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at in the year 0000 at an offset that puts the instant in the year 0001", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "0000-12-31T23:30:00-01:00", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at as JavaScript writes the year 10000", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "+010000-01-01T00:00:00.000Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "calls that are empty are told before an expires_at that is no time", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "tomorrow", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "calls must be a non-empty list for an approval or a question" + }, + { + "name": "an expires_at that is no time is told before a requested_at that is none", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "yesterday", + "expires_at": "tomorrow", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at that is no time is told before details that are not text", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "tomorrow", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac", + "details": 5 + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "details that are not text are told before a requested_at that is no time", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "yesterday", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac", + "details": 5 + }, + "status": 400, + "error": "details must be text" + }, + { + "name": "graph_id of a no-break space", + "event": { + "kind": "approval", + "graph_id": " ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "graph_id is required" + }, + { + "name": "description of an ideographic space", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": " ", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "description is required" + }, + { + "name": "correlation_id of the line and the paragraph separator", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "

", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "correlation_id is required" + }, + { + "name": "summary of every white-space character", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "\t\n\u000b\f\r              

   ", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "summary is required" + }, + { + "name": "graph_id of a byte order mark, a character of a name", + "event": { + "kind": "approval", + "graph_id": "", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "", + "turn": 2 + } + }, + { + "name": "correlation_id of a next-line character, a character of a name", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "…", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "description of a file separator, a character of a name", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "\u001c", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "an advice's summary of a unit separator, a character of a name", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "\u001f", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "accepted": { + "accepted": true, + "kind": "advice", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "the largest turn, in ASCII digits", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2147483647", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2147483647 + } + }, + { + "name": "an advice's turn, the largest", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483647, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "accepted": { + "accepted": true, + "kind": "advice", + "graph_id": "order-assistant", + "turn": 2147483647 + } + }, + { + "name": "a turn one past the largest, in ASCII digits", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2147483648", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of 4294967296", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 4294967296, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of the largest whole number", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 9007199254740991, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn one past the largest whole number", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 9007199254740992, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "an advice's turn one past the largest", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483648, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + } + ], + "click_cases": [ + { + "name": "an approval with a note", + "link": "https://ask.example.test/ask/v1.payload.mac", + "ticket": "v1.payload.mac", + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed the loss" + } + ], + "who": "operator-17", + "url": "https://ask.example.test/ask/reply", + "body": { + "ticket": "v1.payload.mac", + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed the loss" + } + ], + "decided_by": "operator-17" + } + }, + { + "name": "a question's answer", + "link": "https://ask.example.test/ask/v1.plan.mac", + "ticket": "v1.plan.mac", + "decisions": [ + { + "id": "toolu_02B", + "answer": "B" + } + ], + "who": "owner-3", + "url": "https://ask.example.test/ask/reply", + "body": { + "ticket": "v1.plan.mac", + "decisions": [ + { + "id": "toolu_02B", + "answer": "B" + } + ], + "decided_by": "owner-3" + } + }, + { + "name": "a link on a path prefix", + "link": "https://gateway.example.test/agents/ask/v1.x.y", + "ticket": "v1.x.y", + "decisions": [ + { + "id": "c1", + "approved": false + } + ], + "who": "operator-17", + "url": "https://gateway.example.test/agents/ask/reply", + "body": { + "ticket": "v1.x.y", + "decisions": [ + { + "id": "c1", + "approved": false + } + ], + "decided_by": "operator-17" + } + }, + { + "name": "a link that is not a resume link", + "link": "https://ask.example.test/questions/app", + "ticket": "v1.x.y", + "decisions": [ + { + "id": "c1", + "approved": true + } + ], + "who": "operator-17", + "status": 409, + "error": "the row's link does not name a reply endpoint" + } + ], + "feed_cases": [ + { + "name": "the replay and the history over seven rows", + "rows": [ + { + "id": 1, + "seq": 3, + "kind": "approval", + "state": "answered" + }, + { + "id": 2, + "seq": 2, + "kind": "advice", + "state": null + }, + { + "id": 3, + "seq": 5, + "kind": "question", + "state": "open" + }, + { + "id": 4, + "seq": 4, + "kind": "approval", + "state": "expired" + }, + { + "id": 5, + "seq": 7, + "kind": "approval", + "state": "open" + }, + { + "id": 6, + "seq": 6, + "kind": "advice", + "state": null + }, + { + "id": 7, + "seq": 1, + "kind": "approval", + "state": "answered" + } + ], + "queries": [ + { + "before": null, + "limit": 3, + "ids": [ + 5, + 6, + 3 + ], + "seqs": [ + 7, + 6, + 5 + ], + "next": 5, + "more": true + }, + { + "before": 5, + "limit": 3, + "ids": [ + 4, + 1, + 2 + ], + "seqs": [ + 4, + 3, + 2 + ], + "next": 2, + "more": true + }, + { + "before": 2, + "limit": 3, + "ids": [ + 7 + ], + "seqs": [ + 1 + ], + "next": 1, + "more": false + }, + { + "before": 1, + "limit": 3, + "ids": [], + "seqs": [], + "next": null, + "more": false + }, + { + "since": 4, + "limit": 10, + "ids": [ + 3, + 6, + 5 + ], + "seqs": [ + 5, + 6, + 7 + ], + "next": 7, + "more": false + }, + { + "since": 0, + "limit": 2, + "ids": [ + 7, + 2 + ], + "seqs": [ + 1, + 2 + ], + "next": 2, + "more": true + }, + { + "since": 7, + "limit": 5, + "ids": [], + "seqs": [], + "next": 7, + "more": false + } + ] + } + ], + "row_id_cases": [ + { + "name": "digits", + "id": "7", + "row": "7" + }, + { + "name": "zero", + "id": "0", + "row": "0" + }, + { + "name": "leading zeros are digits", + "id": "007", + "row": "7" + }, + { + "name": "nineteen digits, as many as the largest number has", + "id": "0000000000000000007", + "row": "7" + }, + { + "name": "a number past the whole numbers a double holds exactly", + "id": "9007199254740993", + "row": "9007199254740993" + }, + { + "name": "the largest number a BIGINT column holds", + "id": "9223372036854775807", + "row": "9223372036854775807" + }, + { + "name": "one more than the largest number", + "id": "9223372036854775808", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "nineteen nines", + "id": "9999999999999999999", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "twenty digits", + "id": "00000000000000000007", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "four hundred digits", + "id": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space before and after", + "id": " 7 ", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space after", + "id": "7 ", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space before", + "id": " 7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space alone", + "id": " ", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a newline after", + "id": "7\n", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a tab before", + "id": "\t7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space between digits", + "id": "1 0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a minus sign", + "id": "-3", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a plus sign", + "id": "+7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "minus zero", + "id": "-0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an underscore between digits", + "id": "1_0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a thousands separator", + "id": "1,000", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a fraction", + "id": "1.0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a decimal point alone", + "id": "1.", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an exponent", + "id": "1e3", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a hexadecimal prefix", + "id": "0x10", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a binary prefix", + "id": "0b11", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an octal prefix", + "id": "0o17", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a letter", + "id": "x", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "digits then a letter", + "id": "7x", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "the word NaN", + "id": "NaN", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "the word Infinity", + "id": "Infinity", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an Arabic-Indic digit (U+0663)", + "id": "٣", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a Devanagari digit (U+096D)", + "id": "७", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a fullwidth digit (U+FF17)", + "id": "7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a mathematical double-struck digit (U+1D7DF)", + "id": "𝟟", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a superscript two (U+00B2)", + "id": "²", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an ASCII digit then an Arabic-Indic one", + "id": "1٣", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an empty id", + "id": "", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "no id", + "id": null, + "status": 400, + "error": "the row id must be a whole number" + } + ], + "cursor_cases": [ + { + "name": "digits", + "last_event_id": "7", + "since": null, + "cursor": "7" + }, + { + "name": "zero", + "last_event_id": "0", + "since": null, + "cursor": "0" + }, + { + "name": "leading zeros are digits", + "last_event_id": "007", + "since": null, + "cursor": "7" + }, + { + "name": "nineteen digits, as many as the largest number has", + "last_event_id": "0000000000000000007", + "since": null, + "cursor": "7" + }, + { + "name": "a number past the whole numbers a double holds exactly", + "last_event_id": "9007199254740993", + "since": null, + "cursor": "9007199254740993" + }, + { + "name": "the largest number a BIGINT column holds", + "last_event_id": "9223372036854775807", + "since": null, + "cursor": "9223372036854775807" + }, + { + "name": "one more than the largest number", + "last_event_id": "9223372036854775808", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "nineteen nines", + "last_event_id": "9999999999999999999", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "twenty digits", + "last_event_id": "00000000000000000007", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "four hundred digits", + "last_event_id": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space before and after", + "last_event_id": " 7 ", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space after", + "last_event_id": "7 ", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space before", + "last_event_id": " 7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space alone", + "last_event_id": " ", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a newline after", + "last_event_id": "7\n", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a tab before", + "last_event_id": "\t7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space between digits", + "last_event_id": "1 0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a minus sign", + "last_event_id": "-3", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a plus sign", + "last_event_id": "+7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "minus zero", + "last_event_id": "-0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an underscore between digits", + "last_event_id": "1_0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a thousands separator", + "last_event_id": "1,000", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a fraction", + "last_event_id": "1.0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a decimal point alone", + "last_event_id": "1.", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an exponent", + "last_event_id": "1e3", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a hexadecimal prefix", + "last_event_id": "0x10", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a binary prefix", + "last_event_id": "0b11", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an octal prefix", + "last_event_id": "0o17", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a letter", + "last_event_id": "x", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "digits then a letter", + "last_event_id": "7x", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "the word NaN", + "last_event_id": "NaN", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "the word Infinity", + "last_event_id": "Infinity", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an Arabic-Indic digit (U+0663)", + "last_event_id": "٣", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a Devanagari digit (U+096D)", + "last_event_id": "७", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a fullwidth digit (U+FF17)", + "last_event_id": "7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a mathematical double-struck digit (U+1D7DF)", + "last_event_id": "𝟟", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a superscript two (U+00B2)", + "last_event_id": "²", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an ASCII digit then an Arabic-Indic one", + "last_event_id": "1٣", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "no Last-Event-ID and no since: the beginning", + "last_event_id": null, + "since": null, + "cursor": "0" + }, + { + "name": "an empty Last-Event-ID is none", + "last_event_id": "", + "since": null, + "cursor": "0" + }, + { + "name": "since when there is no Last-Event-ID", + "last_event_id": null, + "since": "5", + "cursor": "5" + }, + { + "name": "since when the Last-Event-ID is empty", + "last_event_id": "", + "since": "5", + "cursor": "5" + }, + { + "name": "an empty since is none", + "last_event_id": null, + "since": "", + "cursor": "0" + }, + { + "name": "the Last-Event-ID wins over since", + "last_event_id": "7", + "since": "5", + "cursor": "7" + }, + { + "name": "a Last-Event-ID of zero wins over since", + "last_event_id": "0", + "since": "5", + "cursor": "0" + }, + { + "name": "a Last-Event-ID that is not a cursor is refused though since is one", + "last_event_id": "x", + "since": "5", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since that is not a cursor", + "last_event_id": null, + "since": "x", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since with a minus sign", + "last_event_id": null, + "since": "-3", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since with a fraction", + "last_event_id": null, + "since": "1.0", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since past the largest number", + "last_event_id": null, + "since": "9223372036854775808", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since of the largest number", + "last_event_id": null, + "since": "9223372036854775807", + "cursor": "9223372036854775807" + } + ], + "number_cases": [ + { + "name": "ASCII digits", + "value": "512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a single digit", + "value": "1", + "whole": 1, + "duration_ms": 1000 + }, + { + "name": "zero as text", + "value": "0", + "whole": 0, + "duration_ms": 0 + }, + { + "name": "leading zeros", + "value": "007", + "whole": 7, + "duration_ms": 7000 + }, + { + "name": "forty leading zeros", + "value": "00000000000000000000000000000000000000001", + "whole": 1, + "duration_ms": 1000 + }, + { + "name": "spaces around", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a tab and a newline around", + "value": "\t512\n", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "no-break spaces around", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "an ideographic space before", + "value": " 512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a line separator before", + "value": "
512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a space inside", + "value": "5 12", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark before", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark after", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a next-line character after", + "value": "512…", + "whole": null, + "duration_ms": null + }, + { + "name": "a file separator before", + "value": "\u001c512", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit separator after", + "value": "512\u001f", + "whole": null, + "duration_ms": null + }, + { + "name": "a zero-width space before", + "value": "​512", + "whole": null, + "duration_ms": null + }, + { + "name": "empty text", + "value": "", + "whole": null, + "duration_ms": null + }, + { + "name": "blank text", + "value": " ", + "whole": null, + "duration_ms": null + }, + { + "name": "a plus sign", + "value": "+5", + "whole": null, + "duration_ms": null + }, + { + "name": "a minus sign", + "value": "-5", + "whole": null, + "duration_ms": null + }, + { + "name": "an underscore", + "value": "5_0", + "whole": null, + "duration_ms": null + }, + { + "name": "a point in text", + "value": "5.0", + "whole": null, + "duration_ms": null + }, + { + "name": "an exponent in text", + "value": "5e2", + "whole": null, + "duration_ms": null + }, + { + "name": "hexadecimal text", + "value": "0x10", + "whole": null, + "duration_ms": null + }, + { + "name": "a word", + "value": "five", + "whole": null, + "duration_ms": null + }, + { + "name": "an Arabic-Indic digit", + "value": "٣", + "whole": null, + "duration_ms": null + }, + { + "name": "Arabic-Indic digits", + "value": "٥١٢", + "whole": null, + "duration_ms": null + }, + { + "name": "ASCII then Arabic-Indic", + "value": "5٣", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth digits", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a Devanagari digit", + "value": "५", + "whole": null, + "duration_ms": null + }, + { + "name": "a mathematical bold digit", + "value": "𝟓", + "whole": null, + "duration_ms": null + }, + { + "name": "superscript two", + "value": "²", + "whole": null, + "duration_ms": null + }, + { + "name": "ASCII then superscript", + "value": "5²", + "whole": null, + "duration_ms": null + }, + { + "name": "subscript two", + "value": "₂", + "whole": null, + "duration_ms": null + }, + { + "name": "a circled digit", + "value": "①", + "whole": null, + "duration_ms": null + }, + { + "name": "a vulgar fraction", + "value": "½", + "whole": null, + "duration_ms": null + }, + { + "name": "a Roman numeral", + "value": "Ⅷ", + "whole": null, + "duration_ms": null + }, + { + "name": "an ideographic number", + "value": "五", + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number as text", + "value": "9007199254740991", + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "one above the largest as text", + "value": "9007199254740992", + "whole": null, + "duration_ms": null + }, + { + "name": "twenty nines", + "value": "99999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "four hundred nines", + "value": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "five thousand nines", + "value": "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "a number", + "value": 512, + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "zero", + "value": 0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "a negative number", + "value": -5, + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number", + "value": 9007199254740991, + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "one above the largest", + "value": 9007199254740992, + "whole": null, + "duration_ms": null + }, + { + "name": "a number of twenty nines", + "value": 99999999999999999999, + "whole": null, + "duration_ms": null + }, + { + "name": "a float with a whole value", + "value": 16000.0, + "whole": 16000, + "duration_ms": 16000000 + }, + { + "name": "float zero", + "value": 0.0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "negative zero", + "value": -0.0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "a negative float with a whole value", + "value": -1.0, + "whole": null, + "duration_ms": null + }, + { + "name": "a float with a fraction", + "value": 2.5, + "whole": null, + "duration_ms": null + }, + { + "name": "a float just above a whole value", + "value": 5.000000000000001, + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number as a float", + "value": 9007199254740991.0, + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "a float above the largest", + "value": 1e+16, + "whole": null, + "duration_ms": null + }, + { + "name": "a huge float", + "value": 1e+300, + "whole": null, + "duration_ms": null + }, + { + "name": "true", + "value": true, + "whole": null, + "duration_ms": null + }, + { + "name": "false", + "value": false, + "whole": null, + "duration_ms": null + }, + { + "name": "null", + "value": null, + "whole": null, + "duration_ms": null + }, + { + "name": "a list", + "value": [ + 5 + ], + "whole": null, + "duration_ms": null + }, + { + "name": "a map", + "value": { + "value": 5 + }, + "whole": null, + "duration_ms": null + }, + { + "name": "minutes", + "value": "30m", + "whole": null, + "duration_ms": 1800000 + }, + { + "name": "hours", + "value": "12h", + "whole": null, + "duration_ms": 43200000 + }, + { + "name": "days", + "value": "2d", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "seconds", + "value": "45s", + "whole": null, + "duration_ms": 45000 + }, + { + "name": "zero days", + "value": "0d", + "whole": null, + "duration_ms": 0 + }, + { + "name": "spaces around a duration", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "a space before the unit", + "value": "2 d", + "whole": null, + "duration_ms": null + }, + { + "name": "an upper-case unit", + "value": "2D", + "whole": null, + "duration_ms": null + }, + { + "name": "an unknown unit", + "value": "2w", + "whole": null, + "duration_ms": null + }, + { + "name": "two units", + "value": "1d12h", + "whole": null, + "duration_ms": null + }, + { + "name": "a fraction of an hour", + "value": "1.5h", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit alone", + "value": "d", + "whole": null, + "duration_ms": null + }, + { + "name": "Arabic-Indic hours", + "value": "٣h", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth hours", + "value": "12h", + "whole": null, + "duration_ms": null + }, + { + "name": "a fullwidth unit", + "value": "2d", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark before a duration", + "value": "2d", + "whole": null, + "duration_ms": null + }, + { + "name": "a next-line character after a duration", + "value": "2d…", + "whole": null, + "duration_ms": null + }, + { + "name": "days past the most milliseconds", + "value": "104249991374d", + "whole": null, + "duration_ms": null + }, + { + "name": "a day more past the most milliseconds", + "value": "104249991375d", + "whole": null, + "duration_ms": null + }, + { + "name": "twenty nines of days", + "value": "99999999999999999999d", + "whole": null, + "duration_ms": null + }, + { + "name": "a range of pages", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages and ranges", + "value": "1-3,7", + "whole": null, + "duration_ms": null + }, + { + "name": "pages in the order named", + "value": "7,1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with spaces", + "value": " 2 - 3 , 1 ", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with no-break spaces", + "value": "1 - 3", + "whole": null, + "duration_ms": null + }, + { + "name": "two pages without a comma", + "value": "1 3", + "whole": null, + "duration_ms": null + }, + { + "name": "a space inside a page of a range", + "value": "1 0-12", + "whole": null, + "duration_ms": null + }, + { + "name": "line breaks around a hyphen", + "value": "1\n-\n3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with a byte order mark", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with a next-line character", + "value": "1…-3", + "whole": null, + "duration_ms": null + }, + { + "name": "an Arabic-Indic page", + "value": "1-٣", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth pages", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "a fullwidth hyphen", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "an en dash", + "value": "1–3", + "whole": null, + "duration_ms": null + }, + { + "name": "a range from page zero", + "value": "0-3", + "whole": null, + "duration_ms": null + }, + { + "name": "a range to the largest page", + "value": "1-9007199254740991", + "whole": null, + "duration_ms": null + }, + { + "name": "a range beyond the largest page", + "value": "1-9007199254740992", + "whole": null, + "duration_ms": null + }, + { + "name": "milliseconds", + "value": "500ms", + "whole": null, + "duration_ms": 500 + }, + { + "name": "zero milliseconds", + "value": "0ms", + "whole": null, + "duration_ms": 0 + }, + { + "name": "leading zeros and a unit", + "value": "007m", + "whole": null, + "duration_ms": 420000 + }, + { + "name": "spaces around milliseconds", + "value": " 250ms ", + "whole": null, + "duration_ms": 250 + }, + { + "name": "a space before ms", + "value": "500 ms", + "whole": null, + "duration_ms": null + }, + { + "name": "an upper-case ms", + "value": "500MS", + "whole": null, + "duration_ms": null + }, + { + "name": "ms alone", + "value": "ms", + "whole": null, + "duration_ms": null + }, + { + "name": "ms then s", + "value": "5mss", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit before the number", + "value": "s5", + "whole": null, + "duration_ms": null + }, + { + "name": "a minus sign and a unit", + "value": "-5s", + "whole": null, + "duration_ms": null + }, + { + "name": "a float and a unit", + "value": "5.0s", + "whole": null, + "duration_ms": null + }, + { + "name": "the most milliseconds", + "value": "9007199254740991ms", + "whole": null, + "duration_ms": 9007199254740991 + }, + { + "name": "one millisecond more", + "value": "9007199254740992ms", + "whole": null, + "duration_ms": null + }, + { + "name": "the most seconds", + "value": "9007199254740s", + "whole": null, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more", + "value": "9007199254741s", + "whole": null, + "duration_ms": null + }, + { + "name": "the most seconds without a unit", + "value": "9007199254740", + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more without a unit", + "value": "9007199254741", + "whole": 9007199254741, + "duration_ms": null + }, + { + "name": "the most seconds as a number", + "value": 9007199254740, + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more as a number", + "value": 9007199254741, + "whole": 9007199254741, + "duration_ms": null + }, + { + "name": "the most seconds as a float", + "value": 9007199254740.0, + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "the most minutes", + "value": "150119987579m", + "whole": null, + "duration_ms": 9007199254740000 + }, + { + "name": "one minute more", + "value": "150119987580m", + "whole": null, + "duration_ms": null + }, + { + "name": "the most hours", + "value": "2501999792h", + "whole": null, + "duration_ms": 9007199251200000 + }, + { + "name": "one hour more", + "value": "2501999793h", + "whole": null, + "duration_ms": null + }, + { + "name": "the most days", + "value": "104249991d", + "whole": null, + "duration_ms": 9007199222400000 + }, + { + "name": "one day more", + "value": "104249992d", + "whole": null, + "duration_ms": null + }, + { + "name": "five thousand nines of seconds", + "value": "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999s", + "whole": null, + "duration_ms": null + }, + { + "name": "U+0009 around a number, white space in both runtimes", + "value": "\t512\t", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000A around a number, white space in both runtimes", + "value": "\n512\n", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000B around a number, white space in both runtimes", + "value": "\u000b512\u000b", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000C around a number, white space in both runtimes", + "value": "\f512\f", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000D around a number, white space in both runtimes", + "value": "\r512\r", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+0020 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+00A0 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+1680 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2000 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2001 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2002 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2003 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2004 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2005 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2006 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2007 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2008 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2009 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+200A around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2028 around a number, white space in both runtimes", + "value": "
512
", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2029 around a number, white space in both runtimes", + "value": "
512
", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+202F around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+205F around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+3000 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+0009 around a duration, white space in both runtimes", + "value": "\t2d\t", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+00A0 around a duration, white space in both runtimes", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+2029 around a duration, white space in both runtimes", + "value": "
2d
", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+3000 around a duration, white space in both runtimes", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+001C around a number, white space in neither or in one runtime", + "value": "\u001c512\u001c", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001D around a number, white space in neither or in one runtime", + "value": "\u001d512\u001d", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001E around a number, white space in neither or in one runtime", + "value": "\u001e512\u001e", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001F around a number, white space in neither or in one runtime", + "value": "\u001f512\u001f", + "whole": null, + "duration_ms": null + }, + { + "name": "U+0085 around a number, white space in neither or in one runtime", + "value": "…512…", + "whole": null, + "duration_ms": null + }, + { + "name": "U+180E around a number, white space in neither or in one runtime", + "value": "᠎512᠎", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200B around a number, white space in neither or in one runtime", + "value": "​512​", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200C around a number, white space in neither or in one runtime", + "value": "‌512‌", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200D around a number, white space in neither or in one runtime", + "value": "‍512‍", + "whole": null, + "duration_ms": null + }, + { + "name": "U+2060 around a number, white space in neither or in one runtime", + "value": "⁠512⁠", + "whole": null, + "duration_ms": null + }, + { + "name": "U+FEFF around a number, white space in neither or in one runtime", + "value": "512", + "whole": null, + "duration_ms": null + } + ], + "switch_cases": [ + { + "name": "the boolean true", + "value": true, + "switch": true + }, + { + "name": "the boolean false", + "value": false, + "switch": false + }, + { + "name": "the text true", + "value": "true", + "switch": true + }, + { + "name": "the text false", + "value": "false", + "switch": false + }, + { + "name": "TRUE in upper case", + "value": "TRUE", + "switch": true + }, + { + "name": "FALSE in upper case", + "value": "FALSE", + "switch": false + }, + { + "name": "True with a capital", + "value": "True", + "switch": true + }, + { + "name": "False with a capital", + "value": "False", + "switch": false + }, + { + "name": "tRuE in mixed case", + "value": "tRuE", + "switch": true + }, + { + "name": "fAlSe in mixed case", + "value": "fAlSe", + "switch": false + }, + { + "name": "no value", + "value": null, + "switch": "default" + }, + { + "name": "an empty value", + "value": "", + "switch": "default" + }, + { + "name": "a blank value", + "value": " ", + "switch": null + }, + { + "name": "a space before true", + "value": " true", + "switch": null + }, + { + "name": "a space after true", + "value": "true ", + "switch": null + }, + { + "name": "a newline after false", + "value": "false\n", + "switch": null + }, + { + "name": "yes", + "value": "yes", + "switch": null + }, + { + "name": "no", + "value": "no", + "switch": null + }, + { + "name": "on", + "value": "on", + "switch": null + }, + { + "name": "off", + "value": "off", + "switch": null + }, + { + "name": "the text 1", + "value": "1", + "switch": null + }, + { + "name": "the text 0", + "value": "0", + "switch": null + }, + { + "name": "the letter t", + "value": "t", + "switch": null + }, + { + "name": "the letter f", + "value": "f", + "switch": null + }, + { + "name": "enabled", + "value": "enabled", + "switch": null + }, + { + "name": "maybe", + "value": "maybe", + "switch": null + }, + { + "name": "truefalse", + "value": "truefalse", + "switch": null + }, + { + "name": "the number 1", + "value": 1, + "switch": null + }, + { + "name": "the number 0", + "value": 0, + "switch": null + }, + { + "name": "the number 1.0", + "value": 1.0, + "switch": null + }, + { + "name": "a list holding true", + "value": [ + true + ], + "switch": null + }, + { + "name": "an empty list", + "value": [], + "switch": null + }, + { + "name": "a map", + "value": { + "value": true + }, + "switch": null + }, + { + "name": "fullwidth true", + "value": "true", + "switch": null + }, + { + "name": "true with a Cyrillic e", + "value": "truе", + "switch": null + }, + { + "name": "true with a dotted capital I after it", + "value": "trueİ", + "switch": null + } + ], + "list_cases": [ + { + "name": "nothing named: the replay from the beginning", + "query": {}, + "paging": false, + "cursor": "0", + "limit": 200 + }, + { + "name": "since a cursor", + "query": { + "since": "5" + }, + "paging": false, + "cursor": "5", + "limit": 200 + }, + { + "name": "an empty since is the beginning", + "query": { + "since": "" + }, + "paging": false, + "cursor": "0", + "limit": 200 + }, + { + "name": "since zero", + "query": { + "since": "0" + }, + "paging": false, + "cursor": "0", + "limit": 200 + }, + { + "name": "since with leading zeros", + "query": { + "since": "007" + }, + "paging": false, + "cursor": "7", + "limit": 200 + }, + { + "name": "since a number past the whole numbers a double holds exactly", + "query": { + "since": "9007199254740993" + }, + "paging": false, + "cursor": "9007199254740993", + "limit": 200 + }, + { + "name": "since the largest number the record holds", + "query": { + "since": "9223372036854775807" + }, + "paging": false, + "cursor": "9223372036854775807", + "limit": 200 + }, + { + "name": "since one past the largest number the record holds", + "query": { + "since": "9223372036854775808" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since twenty digits", + "query": { + "since": "00000000000000000007" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since in Arabic-Indic digits", + "query": { + "since": "٣" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since in fullwidth digits", + "query": { + "since": "3" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since a superscript digit", + "query": { + "since": "³" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with a space before and after", + "query": { + "since": " 5 " + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with a newline after", + "query": { + "since": "5\n" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with a plus sign", + "query": { + "since": "+5" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with a minus sign", + "query": { + "since": "-5" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with a fraction", + "query": { + "since": "5.0" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with an exponent", + "query": { + "since": "5e0" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with an underscore", + "query": { + "since": "5_0" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since a word", + "query": { + "since": "x" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "before, empty: the newest page", + "query": { + "before": "" + }, + "paging": true, + "cursor": null, + "limit": 200 + }, + { + "name": "before a cursor", + "query": { + "before": "5", + "limit": "3" + }, + "paging": true, + "cursor": "5", + "limit": 3 + }, + { + "name": "before zero", + "query": { + "before": "0" + }, + "paging": true, + "cursor": "0", + "limit": 200 + }, + { + "name": "before a number past the whole numbers a double holds exactly", + "query": { + "before": "9007199254740993" + }, + "paging": true, + "cursor": "9007199254740993", + "limit": 200 + }, + { + "name": "before the largest number the record holds", + "query": { + "before": "9223372036854775807" + }, + "paging": true, + "cursor": "9223372036854775807", + "limit": 200 + }, + { + "name": "before one past the largest number the record holds", + "query": { + "before": "9223372036854775808" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "before in Arabic-Indic digits", + "query": { + "before": "٣" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "before with a space around", + "query": { + "before": " 5 " + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "before a word", + "query": { + "before": "x" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "before is read, and since is not, when both are named", + "query": { + "before": "5", + "since": "2" + }, + "paging": true, + "cursor": "5", + "limit": 200 + }, + { + "name": "an empty before is the newest page though since is named", + "query": { + "before": "", + "since": "2" + }, + "paging": true, + "cursor": null, + "limit": 200 + }, + { + "name": "a since that is no number is not read when the request pages back", + "query": { + "before": "5", + "since": "x" + }, + "paging": true, + "cursor": "5", + "limit": 200 + }, + { + "name": "a before that is no number is refused though since is one", + "query": { + "before": "x", + "since": "2" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit", + "query": { + "since": "5", + "limit": "1" + }, + "paging": false, + "cursor": "5", + "limit": 1 + }, + { + "name": "an empty limit is the default", + "query": { + "limit": "" + }, + "paging": false, + "cursor": "0", + "limit": 200 + }, + { + "name": "a limit of zero is one row", + "query": { + "limit": "0" + }, + "paging": false, + "cursor": "0", + "limit": 1 + }, + { + "name": "a limit past the most a page takes", + "query": { + "limit": "5000" + }, + "paging": false, + "cursor": "0", + "limit": 1000 + }, + { + "name": "the largest whole number as a limit", + "query": { + "limit": "9007199254740991" + }, + "paging": false, + "cursor": "0", + "limit": 1000 + }, + { + "name": "a limit one past the largest whole number", + "query": { + "limit": "9007199254740992" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit of twenty nines", + "query": { + "limit": "99999999999999999999" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit with white space around it", + "query": { + "limit": " 3\t" + }, + "paging": false, + "cursor": "0", + "limit": 3 + }, + { + "name": "a limit with leading zeros", + "query": { + "limit": "007" + }, + "paging": false, + "cursor": "0", + "limit": 7 + }, + { + "name": "a limit in Arabic-Indic digits", + "query": { + "limit": "٣" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit with a plus sign", + "query": { + "limit": "+3" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit with a minus sign", + "query": { + "limit": "-3" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit with a fraction", + "query": { + "limit": "3.0" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit with a space inside", + "query": { + "limit": "1 0" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit that is a word", + "query": { + "limit": "x" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit that is no number is refused when the request pages back", + "query": { + "before": "", + "limit": "x" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a parameter the entry does not know is not read", + "query": { + "since": "5", + "order": "x" + }, + "paging": false, + "cursor": "5", + "limit": 200 } ], - "click_cases": [ + "page_size_cases": [ { - "name": "an approval with a note", - "link": "https://ask.example.test/ask/v1.payload.mac", - "ticket": "v1.payload.mac", - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "Carrier confirmed the loss" - } - ], - "who": "operator-17", - "url": "https://ask.example.test/ask/reply", - "body": { - "ticket": "v1.payload.mac", - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "Carrier confirmed the loss" - } - ], - "decided_by": "operator-17" - } + "name": "no limit is the default", + "limit": null, + "default": 50, + "most": 200, + "size": 50 }, { - "name": "a question's answer", - "link": "https://ask.example.test/ask/v1.plan.mac", - "ticket": "v1.plan.mac", - "decisions": [ - { - "id": "toolu_02B", - "answer": "B" - } - ], - "who": "owner-3", - "url": "https://ask.example.test/ask/reply", - "body": { - "ticket": "v1.plan.mac", - "decisions": [ - { - "id": "toolu_02B", - "answer": "B" - } - ], - "decided_by": "owner-3" - } + "name": "an empty limit is the default", + "limit": "", + "default": 50, + "most": 200, + "size": 50 }, { - "name": "a link on a path prefix", - "link": "https://gateway.example.test/agents/ask/v1.x.y", - "ticket": "v1.x.y", - "decisions": [ - { - "id": "c1", - "approved": false - } - ], - "who": "operator-17", - "url": "https://gateway.example.test/agents/ask/reply", - "body": { - "ticket": "v1.x.y", - "decisions": [ - { - "id": "c1", - "approved": false - } - ], - "decided_by": "operator-17" - } + "name": "a limit", + "limit": "7", + "default": 50, + "most": 200, + "size": 7 }, { - "name": "a link that is not a resume link", - "link": "https://ask.example.test/questions/app", - "ticket": "v1.x.y", - "decisions": [ - { - "id": "c1", - "approved": true - } - ], - "who": "operator-17", - "status": 409, - "error": "the row's link does not name a reply endpoint" + "name": "a limit of zero is one", + "limit": "0", + "default": 50, + "most": 200, + "size": 1 + }, + { + "name": "a limit past the most", + "limit": "500", + "default": 50, + "most": 200, + "size": 200 + }, + { + "name": "the most", + "limit": "200", + "default": 50, + "most": 200, + "size": 200 + }, + { + "name": "one past the most", + "limit": "201", + "default": 50, + "most": 200, + "size": 200 + }, + { + "name": "the largest whole number", + "limit": "9007199254740991", + "default": 50, + "most": 200, + "size": 200 + }, + { + "name": "one past the largest whole number", + "limit": "9007199254740992", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "four hundred nines", + "limit": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "white space around it", + "limit": " 7\n", + "default": 50, + "most": 200, + "size": 7 + }, + { + "name": "leading zeros", + "limit": "007", + "default": 50, + "most": 200, + "size": 7 + }, + { + "name": "Arabic-Indic digits", + "limit": "٧", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "fullwidth digits", + "limit": "7", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a plus sign", + "limit": "+7", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a minus sign", + "limit": "-7", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a fraction", + "limit": "7.0", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "an exponent", + "limit": "7e0", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "an underscore", + "limit": "7_0", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a space inside", + "limit": "7 0", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a word", + "limit": "seven", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a blank", + "limit": " ", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a byte order mark before", + "limit": "7", + "default": 50, + "most": 200, + "size": null } ], - "feed_cases": [ + "exact_cases": [ { - "name": "the replay and the history over seven rows", + "name": "five rows whose ids and sequences are past the whole numbers a double holds exactly", "rows": [ { - "id": 1, - "seq": 3, + "id": "9007199254740993", + "seq": "9223372036854775806", "kind": "approval", - "state": "answered" + "state": "open" }, { - "id": 2, - "seq": 2, + "id": "9007199254740992", + "seq": "9007199254740993", "kind": "advice", "state": null }, { - "id": 3, - "seq": 5, + "id": "9223372036854775807", + "seq": "9007199254740992", "kind": "question", "state": "open" }, { - "id": 4, - "seq": 4, - "kind": "approval", - "state": "expired" - }, - { - "id": 5, - "seq": 7, + "id": "7", + "seq": "9007199254740991", "kind": "approval", - "state": "open" - }, - { - "id": 6, - "seq": 6, - "kind": "advice", - "state": null + "state": "answered" }, { - "id": 7, - "seq": 1, + "id": "9007199254740994", + "seq": "9223372036854775807", "kind": "approval", - "state": "answered" + "state": "expired" } ], "queries": [ { - "before": null, - "limit": 3, + "since": "0", + "limit": 10, + "ids": [ + "7", + "9223372036854775807", + "9007199254740992", + "9007199254740993", + "9007199254740994" + ], + "seqs": [ + "9007199254740991", + "9007199254740992", + "9007199254740993", + "9223372036854775806", + "9223372036854775807" + ], + "next": "9223372036854775807", + "more": false + }, + { + "since": "9007199254740991", + "limit": 2, "ids": [ - 5, - 6, - 3 + "9223372036854775807", + "9007199254740992" ], "seqs": [ - 7, - 6, - 5 + "9007199254740992", + "9007199254740993" ], - "next": 5, + "next": "9007199254740993", "more": true }, { - "before": 5, - "limit": 3, + "since": "9007199254740992", + "limit": 2, "ids": [ - 4, - 1, - 2 + "9007199254740992", + "9007199254740993" ], "seqs": [ - 4, - 3, - 2 + "9007199254740993", + "9223372036854775806" ], - "next": 2, + "next": "9223372036854775806", "more": true }, { - "before": 2, - "limit": 3, + "since": "9223372036854775806", + "limit": 5, "ids": [ - 7 + "9007199254740994" ], "seqs": [ - 1 + "9223372036854775807" ], - "next": 1, + "next": "9223372036854775807", "more": false }, { - "before": 1, - "limit": 3, + "since": "9223372036854775807", + "limit": 5, "ids": [], "seqs": [], - "next": null, + "next": "9223372036854775807", "more": false }, { - "since": 4, - "limit": 10, + "before": null, + "limit": 2, "ids": [ - 3, - 6, - 5 + "9007199254740994", + "9007199254740993" ], "seqs": [ - 5, - 6, - 7 + "9223372036854775807", + "9223372036854775806" ], - "next": 7, - "more": false + "next": "9223372036854775806", + "more": true }, { - "since": 0, + "before": "9223372036854775807", "limit": 2, "ids": [ - 7, - 2 + "9007199254740993", + "9007199254740992" ], "seqs": [ - 1, - 2 + "9223372036854775806", + "9007199254740993" ], - "next": 2, + "next": "9007199254740993", "more": true }, { - "since": 7, + "before": "9223372036854775806", + "limit": 2, + "ids": [ + "9007199254740992", + "9223372036854775807" + ], + "seqs": [ + "9007199254740993", + "9007199254740992" + ], + "next": "9007199254740992", + "more": true + }, + { + "before": "9007199254740993", + "limit": 5, + "ids": [ + "9223372036854775807", + "7" + ], + "seqs": [ + "9007199254740992", + "9007199254740991" + ], + "next": "9007199254740991", + "more": false + }, + { + "before": "9007199254740992", + "limit": 5, + "ids": [ + "7" + ], + "seqs": [ + "9007199254740991" + ], + "next": "9007199254740991", + "more": false + }, + { + "before": "9007199254740991", "limit": 5, "ids": [], "seqs": [], - "next": 7, + "next": null, "more": false } - ] + ], + "latest": "9223372036854775807" } ], - "row_id_cases": [ + "time_cases": [ + { + "name": "a time in UTC to the second", + "text": "2026-11-20T10:00:00Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "a time in UTC to the millisecond", + "text": "2026-11-20T10:00:00.123Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a time in UTC to the minute", + "text": "2026-11-20T10:00Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "a fraction of one digit", + "text": "2026-11-20T10:00:00.1Z", + "ms": 1795168800100, + "stamp": "2026-11-20T10:00:00.100Z" + }, + { + "name": "a fraction of two digits", + "text": "2026-11-20T10:00:00.12Z", + "ms": 1795168800120, + "stamp": "2026-11-20T10:00:00.120Z" + }, + { + "name": "a fraction of six digits is cut after the third", + "text": "2026-11-20T10:00:00.123456Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a fraction of nine digits is cut after the third", + "text": "2026-11-20T10:00:00.123456789Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a fraction that would round up is cut", + "text": "2026-11-20T10:00:00.9996Z", + "ms": 1795168800999, + "stamp": "2026-11-20T10:00:00.999Z" + }, + { + "name": "a fraction of nine nines", + "text": "2026-11-20T23:59:59.999999999Z", + "ms": 1795219199999, + "stamp": "2026-11-20T23:59:59.999Z" + }, + { + "name": "a fraction of zeros", + "text": "2026-11-20T10:00:00.000Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "an offset ahead of UTC", + "text": "2026-11-20T10:00:00+01:00", + "ms": 1795165200000, + "stamp": "2026-11-20T09:00:00.000Z" + }, + { + "name": "an offset behind UTC", + "text": "2026-11-20T10:00:00-08:00", + "ms": 1795197600000, + "stamp": "2026-11-20T18:00:00.000Z" + }, + { + "name": "an offset of half an hour", + "text": "2026-11-20T10:00:00+05:30", + "ms": 1795149000000, + "stamp": "2026-11-20T04:30:00.000Z" + }, + { + "name": "an offset of three quarters of an hour", + "text": "2026-11-20T10:00:00.5+05:45", + "ms": 1795148100500, + "stamp": "2026-11-20T04:15:00.500Z" + }, + { + "name": "the largest offset ahead of UTC", + "text": "2026-11-20T10:00:00+23:59", + "ms": 1795082460000, + "stamp": "2026-11-19T10:01:00.000Z" + }, + { + "name": "the largest offset behind UTC", + "text": "2026-11-20T10:00:00-23:59", + "ms": 1795255140000, + "stamp": "2026-11-21T09:59:00.000Z" + }, + { + "name": "an offset of plus nothing", + "text": "2026-11-20T10:00:00+00:00", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "an offset of minus nothing", + "text": "2026-11-20T10:00:00-00:00", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "to the minute at an offset", + "text": "2026-11-20T10:00+01:00", + "ms": 1795165200000, + "stamp": "2026-11-20T09:00:00.000Z" + }, + { + "name": "an offset that crosses midnight into the year before", + "text": "2026-01-01T00:30:00+01:00", + "ms": 1767223800000, + "stamp": "2025-12-31T23:30:00.000Z" + }, + { + "name": "an offset that crosses midnight into the year after", + "text": "2026-12-31T23:30:00-01:00", + "ms": 1798763400000, + "stamp": "2027-01-01T00:30:00.000Z" + }, + { + "name": "an offset that crosses the 29th of February", + "text": "2024-03-01T00:00:00+00:01", + "ms": 1709251140000, + "stamp": "2024-02-29T23:59:00.000Z" + }, + { + "name": "midnight", + "text": "2026-11-20T00:00:00Z", + "ms": 1795132800000, + "stamp": "2026-11-20T00:00:00.000Z" + }, + { + "name": "the last second of a day", + "text": "2026-11-20T23:59:59Z", + "ms": 1795219199000, + "stamp": "2026-11-20T23:59:59.000Z" + }, + { + "name": "the 29th of February of a leap year", + "text": "2024-02-29T12:00:00Z", + "ms": 1709208000000, + "stamp": "2024-02-29T12:00:00.000Z" + }, + { + "name": "the 29th of February of the year 2000", + "text": "2000-02-29T12:00:00Z", + "ms": 951825600000, + "stamp": "2000-02-29T12:00:00.000Z" + }, + { + "name": "the 29th of February of the year 0004", + "text": "0004-02-29T12:00:00Z", + "ms": -62035848000000, + "stamp": "0004-02-29T12:00:00.000Z" + }, + { + "name": "the 31st of January", + "text": "2026-01-31T12:00:00Z", + "ms": 1769860800000, + "stamp": "2026-01-31T12:00:00.000Z" + }, + { + "name": "the 30th of April", + "text": "2026-04-30T12:00:00Z", + "ms": 1777550400000, + "stamp": "2026-04-30T12:00:00.000Z" + }, + { + "name": "the 31st of December", + "text": "2026-12-31T12:00:00Z", + "ms": 1798718400000, + "stamp": "2026-12-31T12:00:00.000Z" + }, + { + "name": "the first instant of 1970", + "text": "1970-01-01T00:00:00Z", + "ms": 0, + "stamp": "1970-01-01T00:00:00.000Z" + }, + { + "name": "an instant before 1970", + "text": "1969-12-31T23:59:59.250Z", + "ms": -750, + "stamp": "1969-12-31T23:59:59.250Z" + }, + { + "name": "a year before 1000", + "text": "0999-12-31T23:59:59Z", + "ms": -30610224001000, + "stamp": "0999-12-31T23:59:59.000Z" + }, + { + "name": "a year of two significant digits", + "text": "0033-04-03T15:00:00+02:00", + "ms": -61117758000000, + "stamp": "0033-04-03T13:00:00.000Z" + }, + { + "name": "the first instant both packs write", + "text": "0001-01-01T00:00:00Z", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant both packs write", + "text": "9999-12-31T23:59:59.999Z", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the last instant, with a longer fraction", + "text": "9999-12-31T23:59:59.999999999Z", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the first instant, written at an offset", + "text": "0001-01-01T00:01:00+00:01", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant, written at an offset", + "text": "9999-12-31T23:58:59.999-00:01", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the first instant, written a day later at the largest offset", + "text": "0001-01-01T23:59:00+23:59", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant, written a day earlier at the largest offset", + "text": "9999-12-31T00:00:59.999-23:59", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "no offset", + "text": "2026-11-20T10:00:00", + "ms": null, + "stamp": null + }, + { + "name": "no offset, to the minute", + "text": "2026-11-20T10:00", + "ms": null, + "stamp": null + }, + { + "name": "no offset, with a fraction", + "text": "2026-11-20T10:00:00.123", + "ms": null, + "stamp": null + }, + { + "name": "a date alone", + "text": "2026-11-20", + "ms": null, + "stamp": null + }, + { + "name": "a time alone", + "text": "10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a lower-case t", + "text": "2026-11-20t10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a lower-case z", + "text": "2026-11-20T10:00:00z", + "ms": null, + "stamp": null + }, + { + "name": "a space for the T", + "text": "2026-11-20 10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an underscore for the T", + "text": "2026-11-20_10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a space before", + "text": " 2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a space after", + "text": "2026-11-20T10:00:00Z ", + "ms": null, + "stamp": null + }, + { + "name": "a newline after", + "text": "2026-11-20T10:00:00Z\n", + "ms": null, + "stamp": null + }, + { + "name": "a carriage return and a newline after", + "text": "2026-11-20T10:00:00Z\r\n", + "ms": null, + "stamp": null + }, + { + "name": "a tab before", + "text": "\t2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a no-break space after", + "text": "2026-11-20T10:00:00Z ", + "ms": null, + "stamp": null + }, + { + "name": "a byte order mark before", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a next-line character after", + "text": "2026-11-20T10:00:00Z…", + "ms": null, + "stamp": null + }, + { + "name": "a NUL after", + "text": "2026-11-20T10:00:00Z\u0000", + "ms": null, + "stamp": null + }, + { + "name": "a space before the offset", + "text": "2026-11-20T10:00:00 +01:00", + "ms": null, + "stamp": null + }, + { + "name": "a space before the Z", + "text": "2026-11-20T10:00:00 Z", + "ms": null, + "stamp": null + }, + { + "name": "the basic format", + "text": "20261120T100000Z", + "ms": null, + "stamp": null + }, + { + "name": "the basic format of the time alone", + "text": "2026-11-20T100000Z", + "ms": null, + "stamp": null + }, + { + "name": "a week date", + "text": "2026-W47-5", + "ms": null, + "stamp": null + }, + { + "name": "a week date with a time", + "text": "2026-W47-5T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an ordinal date", + "text": "2026-324T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the hour alone", + "text": "2026-11-20T10Z", + "ms": null, + "stamp": null + }, + { + "name": "a comma for the point", + "text": "2026-11-20T10:00:00,5Z", + "ms": null, + "stamp": null + }, + { + "name": "a fraction of the minute", + "text": "2026-11-20T10:00.5Z", + "ms": null, + "stamp": null + }, + { + "name": "a point without digits", + "text": "2026-11-20T10:00:00.Z", + "ms": null, + "stamp": null + }, + { + "name": "a fraction of ten digits", + "text": "2026-11-20T10:00:00.1234567891Z", + "ms": null, + "stamp": null + }, + { + "name": "an offset in hours alone", + "text": "2026-11-20T10:00:00+01", + "ms": null, + "stamp": null + }, + { + "name": "an offset without its colon", + "text": "2026-11-20T10:00:00+0100", + "ms": null, + "stamp": null + }, + { + "name": "an offset with seconds", + "text": "2026-11-20T10:00:00+01:00:00", + "ms": null, + "stamp": null + }, + { + "name": "an offset of one digit an hour", + "text": "2026-11-20T10:00:00+1:00", + "ms": null, + "stamp": null + }, + { + "name": "an offset without a sign", + "text": "2026-11-20T10:00:0001:00", + "ms": null, + "stamp": null + }, + { + "name": "a zone's name after the offset", + "text": "2026-11-20T10:00:00+01:00[Europe/Paris]", + "ms": null, + "stamp": null + }, + { + "name": "a Z and an offset", + "text": "2026-11-20T10:00:00Z+01:00", + "ms": null, + "stamp": null + }, + { + "name": "two Zs", + "text": "2026-11-20T10:00:00ZZ", + "ms": null, + "stamp": null + }, + { + "name": "UTC for the Z", + "text": "2026-11-20T10:00:00UTC", + "ms": null, + "stamp": null + }, + { + "name": "GMT after a space", + "text": "2026-11-20T10:00:00 GMT", + "ms": null, + "stamp": null + }, + { + "name": "a date of the HTTP kind", + "text": "Fri, 20 Nov 2026 10:00:00 GMT", + "ms": null, + "stamp": null + }, + { + "name": "a date with slashes", + "text": "2026/11/20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a date with points", + "text": "2026.11.20T10:00:00Z", + "ms": null, + "stamp": null + }, { - "name": "digits", - "id": "7", - "row": "7" + "name": "the day before the month", + "text": "20-11-2026T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "zero", - "id": "0", - "row": "0" + "name": "a time with points", + "text": "2026-11-20T10.00.00Z", + "ms": null, + "stamp": null }, { - "name": "leading zeros are digits", - "id": "007", - "row": "7" + "name": "the seconds from 1970 in digits", + "text": "1795168800", + "ms": null, + "stamp": null }, { - "name": "nineteen digits, as many as the largest number has", - "id": "0000000000000000007", - "row": "7" + "name": "the milliseconds from 1970 in digits", + "text": "1795168800000", + "ms": null, + "stamp": null }, { - "name": "a number past the whole numbers a double holds exactly", - "id": "9007199254740993", - "row": "9007199254740993" + "name": "a word", + "text": "yesterday", + "ms": null, + "stamp": null }, { - "name": "the largest number a BIGINT column holds", - "id": "9223372036854775807", - "row": "9223372036854775807" + "name": "the word now", + "text": "now", + "ms": null, + "stamp": null }, { - "name": "one more than the largest number", - "id": "9223372036854775808", - "status": 400, - "error": "the row id must be a whole number" + "name": "empty text", + "text": "", + "ms": null, + "stamp": null }, { - "name": "nineteen nines", - "id": "9999999999999999999", - "status": 400, - "error": "the row id must be a whole number" + "name": "a T alone", + "text": "T", + "ms": null, + "stamp": null }, { - "name": "twenty digits", - "id": "00000000000000000007", - "status": 400, - "error": "the row id must be a whole number" + "name": "two times", + "text": "2026-11-20T10:00:00Z2026-11-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "four hundred digits", - "id": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", - "status": 400, - "error": "the row id must be a whole number" + "name": "a time and a word", + "text": "2026-11-20T10:00:00Z tomorrow", + "ms": null, + "stamp": null }, { - "name": "a space before and after", - "id": " 7 ", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 30th of February", + "text": "2026-02-30T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a space after", - "id": "7 ", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 29th of February of a common year", + "text": "2026-02-29T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a space before", - "id": " 7", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 29th of February of the year 1900", + "text": "1900-02-29T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a space alone", - "id": " ", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 29th of February of the year 2100", + "text": "2100-02-29T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a newline after", - "id": "7\n", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 31st of April", + "text": "2026-04-31T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a tab before", - "id": "\t7", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 31st of November", + "text": "2026-11-31T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a space between digits", - "id": "1 0", - "status": 400, - "error": "the row id must be a whole number" + "name": "a month of nothing", + "text": "2026-00-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a minus sign", - "id": "-3", - "status": 400, - "error": "the row id must be a whole number" + "name": "a thirteenth month", + "text": "2026-13-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a plus sign", - "id": "+7", - "status": 400, - "error": "the row id must be a whole number" + "name": "a day of nothing", + "text": "2026-11-00T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "minus zero", - "id": "-0", - "status": 400, - "error": "the row id must be a whole number" + "name": "a 32nd day", + "text": "2026-11-32T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "an underscore between digits", - "id": "1_0", - "status": 400, - "error": "the row id must be a whole number" + "name": "hour 24, minute nothing", + "text": "2026-11-20T24:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a thousands separator", - "id": "1,000", - "status": 400, - "error": "the row id must be a whole number" + "name": "hour 24", + "text": "2026-11-20T24:30:00Z", + "ms": null, + "stamp": null }, { - "name": "a fraction", - "id": "1.0", - "status": 400, - "error": "the row id must be a whole number" + "name": "hour 25", + "text": "2026-11-20T25:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a decimal point alone", - "id": "1.", - "status": 400, - "error": "the row id must be a whole number" + "name": "minute 60", + "text": "2026-11-20T10:60:00Z", + "ms": null, + "stamp": null }, { - "name": "an exponent", - "id": "1e3", - "status": 400, - "error": "the row id must be a whole number" + "name": "second 60, a leap second", + "text": "2026-12-31T23:59:60Z", + "ms": null, + "stamp": null }, { - "name": "a hexadecimal prefix", - "id": "0x10", - "status": 400, - "error": "the row id must be a whole number" + "name": "second 61", + "text": "2026-11-20T10:00:61Z", + "ms": null, + "stamp": null }, { - "name": "a binary prefix", - "id": "0b11", - "status": 400, - "error": "the row id must be a whole number" + "name": "an offset of 24 hours", + "text": "2026-11-20T10:00:00+24:00", + "ms": null, + "stamp": null }, { - "name": "an octal prefix", - "id": "0o17", - "status": 400, - "error": "the row id must be a whole number" + "name": "an offset with 60 minutes", + "text": "2026-11-20T10:00:00+01:60", + "ms": null, + "stamp": null }, { - "name": "a letter", - "id": "x", - "status": 400, - "error": "the row id must be a whole number" + "name": "an offset of 99 hours", + "text": "2026-11-20T10:00:00-99:59", + "ms": null, + "stamp": null }, { - "name": "digits then a letter", - "id": "7x", - "status": 400, - "error": "the row id must be a whole number" + "name": "the year nothing", + "text": "0000-01-01T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "the word NaN", - "id": "NaN", - "status": 400, - "error": "the row id must be a whole number" + "name": "the last day of the year nothing", + "text": "0000-12-31T23:59:59Z", + "ms": null, + "stamp": null }, { - "name": "the word Infinity", - "id": "Infinity", - "status": 400, - "error": "the row id must be a whole number" + "name": "the year nothing, at an offset that puts the instant in the year 0001", + "text": "0000-12-31T23:30:00-01:00", + "ms": null, + "stamp": null }, { - "name": "an Arabic-Indic digit (U+0663)", - "id": "٣", - "status": 400, - "error": "the row id must be a whole number" + "name": "a year of five digits", + "text": "10000-01-01T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a Devanagari digit (U+096D)", - "id": "७", - "status": 400, - "error": "the row id must be a whole number" + "name": "a year of six digits with a sign", + "text": "+002026-11-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a fullwidth digit (U+FF17)", - "id": "7", - "status": 400, - "error": "the row id must be a whole number" + "name": "a year before nothing", + "text": "-0001-11-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a mathematical double-struck digit (U+1D7DF)", - "id": "𝟟", - "status": 400, - "error": "the row id must be a whole number" + "name": "a year of two digits", + "text": "26-11-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a superscript two (U+00B2)", - "id": "²", - "status": 400, - "error": "the row id must be a whole number" + "name": "a year of three digits", + "text": "999-12-31T23:59:59Z", + "ms": null, + "stamp": null }, { - "name": "an ASCII digit then an Arabic-Indic one", - "id": "1٣", - "status": 400, - "error": "the row id must be a whole number" + "name": "a month of one digit", + "text": "2026-1-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a day of one digit", + "text": "2026-11-2T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an hour of one digit", + "text": "2026-11-20T9:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a minute of one digit", + "text": "2026-11-20T10:0:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a second of one digit", + "text": "2026-11-20T10:00:0Z", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts before the year 0001", + "text": "0001-01-01T00:00:00+00:01", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts a day before the year 0001", + "text": "0001-01-01T23:58:59.999+23:59", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts past the year 9999", + "text": "9999-12-31T23:59:59-00:01", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts a day past the year 9999", + "text": "9999-12-31T00:01:00-23:59", + "ms": null, + "stamp": null + }, + { + "name": "Arabic-Indic digits in the year", + "text": "٢٠٢٦-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an Arabic-Indic digit in the second", + "text": "2026-11-20T10:00:0٠Z", + "ms": null, + "stamp": null + }, + { + "name": "fullwidth digits in the day", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth digit in the fraction", + "text": "2026-11-20T10:00:00.1Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth digit in the offset", + "text": "2026-11-20T10:00:00+01:00", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth colon", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth T", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth Z", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a minus sign of the mathematical kind in the offset", + "text": "2026-11-20T10:00:00−01:00", + "ms": null, + "stamp": null + }, + { + "name": "an en dash in the date", + "text": "2026–11–20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a superscript digit", + "text": "2026-11-20T10:00:0²Z", + "ms": null, + "stamp": null + }, + { + "name": "a lone surrogate after", + "text": "2026-11-20T10:00:00Z\ud800", + "ms": null, + "stamp": null + } + ], + "text_cases": [ + { + "name": "empty text", + "text": "", + "trimmed": "", + "blank": true + }, + { + "name": "a name", + "text": "order-assistant", + "trimmed": "order-assistant", + "blank": false + }, + { + "name": "a name with a space inside", + "text": "order assistant", + "trimmed": "order assistant", + "blank": false + }, + { + "name": "U+0009 alone, white space in both runtimes", + "text": "\t", + "trimmed": "", + "blank": true + }, + { + "name": "U+0009 around a name, white space in both runtimes", + "text": "\tname\t", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000A alone, white space in both runtimes", + "text": "\n", + "trimmed": "", + "blank": true + }, + { + "name": "U+000A around a name, white space in both runtimes", + "text": "\nname\n", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000B alone, white space in both runtimes", + "text": "\u000b", + "trimmed": "", + "blank": true + }, + { + "name": "U+000B around a name, white space in both runtimes", + "text": "\u000bname\u000b", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000C alone, white space in both runtimes", + "text": "\f", + "trimmed": "", + "blank": true + }, + { + "name": "U+000C around a name, white space in both runtimes", + "text": "\fname\f", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000D alone, white space in both runtimes", + "text": "\r", + "trimmed": "", + "blank": true + }, + { + "name": "U+000D around a name, white space in both runtimes", + "text": "\rname\r", + "trimmed": "name", + "blank": false + }, + { + "name": "U+0020 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+0020 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+00A0 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+00A0 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+1680 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+1680 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2000 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2000 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2001 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2001 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2002 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2002 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2003 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2003 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2004 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2004 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2005 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2005 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2006 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2006 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2007 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2007 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "an empty id", - "id": "", - "status": 400, - "error": "the row id must be a whole number" + "name": "U+2008 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "no id", - "id": null, - "status": 400, - "error": "the row id must be a whole number" - } - ], - "cursor_cases": [ + "name": "U+2008 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, { - "name": "digits", - "last_event_id": "7", - "since": null, - "cursor": "7" + "name": "U+2009 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "zero", - "last_event_id": "0", - "since": null, - "cursor": "0" + "name": "U+2009 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "leading zeros are digits", - "last_event_id": "007", - "since": null, - "cursor": "7" + "name": "U+200A alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "nineteen digits, as many as the largest number has", - "last_event_id": "0000000000000000007", - "since": null, - "cursor": "7" + "name": "U+200A around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "a number past the whole numbers a double holds exactly", - "last_event_id": "9007199254740993", - "since": null, - "cursor": "9007199254740993" + "name": "U+2028 alone, white space in both runtimes", + "text": "
", + "trimmed": "", + "blank": true }, { - "name": "the largest number a BIGINT column holds", - "last_event_id": "9223372036854775807", - "since": null, - "cursor": "9223372036854775807" + "name": "U+2028 around a name, white space in both runtimes", + "text": "
name
", + "trimmed": "name", + "blank": false }, { - "name": "one more than the largest number", - "last_event_id": "9223372036854775808", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+2029 alone, white space in both runtimes", + "text": "
", + "trimmed": "", + "blank": true }, { - "name": "nineteen nines", - "last_event_id": "9999999999999999999", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+2029 around a name, white space in both runtimes", + "text": "
name
", + "trimmed": "name", + "blank": false }, { - "name": "twenty digits", - "last_event_id": "00000000000000000007", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+202F alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "four hundred digits", - "last_event_id": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+202F around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "a space before and after", - "last_event_id": " 7 ", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+205F alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "a space after", - "last_event_id": "7 ", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+205F around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "a space before", - "last_event_id": " 7", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+3000 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "a space alone", - "last_event_id": " ", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+3000 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "a newline after", - "last_event_id": "7\n", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001C alone, a character of a name", + "text": "\u001c", + "trimmed": "\u001c", + "blank": false }, { - "name": "a tab before", - "last_event_id": "\t7", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001C around a name, a character of a name", + "text": "\u001cname\u001c", + "trimmed": "\u001cname\u001c", + "blank": false }, { - "name": "a space between digits", - "last_event_id": "1 0", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001D alone, a character of a name", + "text": "\u001d", + "trimmed": "\u001d", + "blank": false }, { - "name": "a minus sign", - "last_event_id": "-3", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001D around a name, a character of a name", + "text": "\u001dname\u001d", + "trimmed": "\u001dname\u001d", + "blank": false }, { - "name": "a plus sign", - "last_event_id": "+7", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001E alone, a character of a name", + "text": "\u001e", + "trimmed": "\u001e", + "blank": false }, { - "name": "minus zero", - "last_event_id": "-0", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001E around a name, a character of a name", + "text": "\u001ename\u001e", + "trimmed": "\u001ename\u001e", + "blank": false }, { - "name": "an underscore between digits", - "last_event_id": "1_0", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001F alone, a character of a name", + "text": "\u001f", + "trimmed": "\u001f", + "blank": false }, { - "name": "a thousands separator", - "last_event_id": "1,000", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001F around a name, a character of a name", + "text": "\u001fname\u001f", + "trimmed": "\u001fname\u001f", + "blank": false }, { - "name": "a fraction", - "last_event_id": "1.0", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+0085 alone, a character of a name", + "text": "…", + "trimmed": "…", + "blank": false }, { - "name": "a decimal point alone", - "last_event_id": "1.", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+0085 around a name, a character of a name", + "text": "…name…", + "trimmed": "…name…", + "blank": false }, { - "name": "an exponent", - "last_event_id": "1e3", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+FEFF alone, a character of a name", + "text": "", + "trimmed": "", + "blank": false }, { - "name": "a hexadecimal prefix", - "last_event_id": "0x10", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+FEFF around a name, a character of a name", + "text": "name", + "trimmed": "name", + "blank": false }, { - "name": "a binary prefix", - "last_event_id": "0b11", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+180E alone, a character of a name", + "text": "᠎", + "trimmed": "᠎", + "blank": false }, { - "name": "an octal prefix", - "last_event_id": "0o17", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+180E around a name, a character of a name", + "text": "᠎name᠎", + "trimmed": "᠎name᠎", + "blank": false }, { - "name": "a letter", - "last_event_id": "x", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200B alone, a character of a name", + "text": "​", + "trimmed": "​", + "blank": false }, { - "name": "digits then a letter", - "last_event_id": "7x", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200B around a name, a character of a name", + "text": "​name​", + "trimmed": "​name​", + "blank": false }, { - "name": "the word NaN", - "last_event_id": "NaN", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200C alone, a character of a name", + "text": "‌", + "trimmed": "‌", + "blank": false }, { - "name": "the word Infinity", - "last_event_id": "Infinity", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200C around a name, a character of a name", + "text": "‌name‌", + "trimmed": "‌name‌", + "blank": false }, { - "name": "an Arabic-Indic digit (U+0663)", - "last_event_id": "٣", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200D alone, a character of a name", + "text": "‍", + "trimmed": "‍", + "blank": false }, { - "name": "a Devanagari digit (U+096D)", - "last_event_id": "७", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200D around a name, a character of a name", + "text": "‍name‍", + "trimmed": "‍name‍", + "blank": false }, { - "name": "a fullwidth digit (U+FF17)", - "last_event_id": "7", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+2060 alone, a character of a name", + "text": "⁠", + "trimmed": "⁠", + "blank": false }, { - "name": "a mathematical double-struck digit (U+1D7DF)", - "last_event_id": "𝟟", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+2060 around a name, a character of a name", + "text": "⁠name⁠", + "trimmed": "⁠name⁠", + "blank": false }, { - "name": "a superscript two (U+00B2)", - "last_event_id": "²", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+0000 alone, a character of a name", + "text": "\u0000", + "trimmed": "\u0000", + "blank": false }, { - "name": "an ASCII digit then an Arabic-Indic one", - "last_event_id": "1٣", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+0000 around a name, a character of a name", + "text": "\u0000name\u0000", + "trimmed": "\u0000name\u0000", + "blank": false }, { - "name": "no Last-Event-ID and no since: the beginning", - "last_event_id": null, - "since": null, - "cursor": "0" + "name": "U+007F alone, a character of a name", + "text": "", + "trimmed": "", + "blank": false }, { - "name": "an empty Last-Event-ID is none", - "last_event_id": "", - "since": null, - "cursor": "0" + "name": "U+007F around a name, a character of a name", + "text": "name", + "trimmed": "name", + "blank": false }, { - "name": "since when there is no Last-Event-ID", - "last_event_id": null, - "since": "5", - "cursor": "5" + "name": "every white-space character and nothing else", + "text": "\t\n\u000b\f\r              

   ", + "trimmed": "", + "blank": true }, { - "name": "since when the Last-Event-ID is empty", - "last_event_id": "", - "since": "5", - "cursor": "5" + "name": "every white-space character around a name", + "text": "\t\n\u000b\f\r              

   name\t\n\u000b\f\r              

   ", + "trimmed": "name", + "blank": false }, { - "name": "an empty since is none", - "last_event_id": null, - "since": "", - "cursor": "0" + "name": "white space before a name only", + "text": " \t name", + "trimmed": "name", + "blank": false }, { - "name": "the Last-Event-ID wins over since", - "last_event_id": "7", - "since": "5", - "cursor": "7" + "name": "white space after a name only", + "text": "name\r\n", + "trimmed": "name", + "blank": false }, { - "name": "a Last-Event-ID of zero wins over since", - "last_event_id": "0", - "since": "5", - "cursor": "0" + "name": "white space inside a name is kept", + "text": " order assistant ", + "trimmed": "order assistant", + "blank": false }, { - "name": "a Last-Event-ID that is not a cursor is refused though since is one", - "last_event_id": "x", - "since": "5", - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "a byte order mark inside white space", + "text": "  ", + "trimmed": "", + "blank": false }, { - "name": "a since that is not a cursor", - "last_event_id": null, - "since": "x", - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "white space inside two byte order marks", + "text": " ", + "trimmed": " ", + "blank": false }, { - "name": "a since with a minus sign", - "last_event_id": null, - "since": "-3", - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "a next-line character after white space", + "text": "name …", + "trimmed": "name …", + "blank": false }, { - "name": "a since with a fraction", - "last_event_id": null, - "since": "1.0", - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "a unit separator before white space", + "text": "\u001f name", + "trimmed": "\u001f name", + "blank": false }, { - "name": "a since past the largest number", - "last_event_id": null, - "since": "9223372036854775808", - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "fifty spaces", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "a since of the largest number", - "last_event_id": null, - "since": "9223372036854775807", - "cursor": "9223372036854775807" + "name": "a name between fifty spaces", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "a lone surrogate between spaces", + "text": " \ud800 ", + "trimmed": "\ud800", + "blank": false } ] } diff --git a/tests/vectors/ask-person-vectors.json b/tests/vectors/ask-person-vectors.json index 0346e62..fd07c67 100644 --- a/tests/vectors/ask-person-vectors.json +++ b/tests/vectors/ask-person-vectors.json @@ -1,7 +1,7 @@ { "contract": "ask-person", - "version": 3, - "description": "The ask-a-person main flow's shared vectors (RFC-0014, build plan step 1): the pure half of extensions/ask-person, run by mercury-python and mercury-nodejs against the same file. ticket_cases pin the ticket a payload and a key produce (v1..: the canonical JSON of the payload - keys sorted, no spaces, Unicode kept - and its HMAC-SHA256, both base64url without padding). verify_cases pin how a ticket is read with a list of keys (the current key first, then the previous one) at a given time: the payload, or the exact status and message that refuse it (400 malformed or another version, 403 no key signs it, 410 expired). message_cases pin the message a hold node sends - validated in a fixed order - and the event the channels receive, with requested_at given so the ticket, the link and expires_at are deterministic; or the exact 400 that refuses it. readvice_cases and reply_cases pin the requests the reply page and endpoint send to the engine's entry (the allowlist by graph id, the correlation id header, the turn, the decisions with who decided and when prefixed to each tool call's note; a question's answer unchanged), or the exact refusal. outcome_cases pin what the invoker gets back from the engine's status and body. No HTTP is exchanged by these cases; the transports are tested by each pack against a fake engine. Version 2 (round 4 - the question record): record_cases pin the row a message event becomes in the record (a wait open with its ticket, link and expiry; an advice with none and no state); answer_cases pin the state an answer's outcome leaves (the engine accepted it: answered; nothing was waiting: expired; a refusal or an engine that did not answer: open); transition_cases pin the record's transitions on a scripted sequence - a wait upserted on (graph_id, correlation_id, turn) unless an older message lands late, an advice appended, the first accepted decision standing, the expiry sweep, the change sequence a feed reads from. Version 3 (a ticket has one spelling): a ticket is well-formed only when it has the three parts and its payload and signature parts are canonical base64url without padding - the alphabet from start to end, and the one spelling the encoder gives the bytes - the signature as long as the MAC (32 bytes, 43 characters); a ticket that is not well-formed is the 400 whatever it resembles, and the 403 is a well-formed ticket that no key signs. ticket_cases gain a payload part of each length base64url without padding can have (4n characters, 4n+2 and 4n+3) and one that holds - and _; verify_cases gain the mangled tickets made from them - a newline, a character more or fewer, padding, the standard alphabet, bits left over in a last character, a part missing, empty or added, another version - each with the status it gets. One earlier case changed with the rule: the signature of 'a tampered signature' left bits over in its last character, so it is now tampered in canonical form (403) and its earlier ticket is the case after it (400).", + "version": 5, + "description": "The ask-a-person main flow's shared vectors (RFC-0014, build plan step 1): the pure half of extensions/ask-person, run by mercury-python and mercury-nodejs against the same file. ticket_cases pin the ticket a payload and a key produce (v1..: the canonical JSON of the payload - keys sorted, no spaces, Unicode kept - and its HMAC-SHA256, both base64url without padding). verify_cases pin how a ticket is read with a list of keys (the current key first, then the previous one) at a given time: the payload, or the exact status and message that refuse it (400 malformed or another version, 403 no key signs it, 410 expired). message_cases pin the message a hold node sends - validated in a fixed order - and the event the channels receive, with requested_at given so the ticket, the link and expires_at are deterministic; or the exact 400 that refuses it. readvice_cases and reply_cases pin the requests the reply page and endpoint send to the engine's entry (the allowlist by graph id, the correlation id header, the turn, the decisions with who decided and when prefixed to each tool call's note; a question's answer unchanged), or the exact refusal. outcome_cases pin what the invoker gets back from the engine's status and body. No HTTP is exchanged by these cases; the transports are tested by each pack against a fake engine. Version 2 (round 4 - the question record): record_cases pin the row a message event becomes in the record (a wait open with its ticket, link and expiry; an advice with none and no state); answer_cases pin the state an answer's outcome leaves (the engine accepted it: answered; nothing was waiting: expired; a refusal or an engine that did not answer: open); transition_cases pin the record's transitions on a scripted sequence - a wait upserted on (graph_id, correlation_id, turn) unless an older message lands late, an advice appended, the first accepted decision standing, the expiry sweep, the change sequence a feed reads from. Version 3 (a ticket has one spelling): a ticket is well-formed only when it has the three parts and its payload and signature parts are canonical base64url without padding - the alphabet from start to end, and the one spelling the encoder gives the bytes - the signature as long as the MAC (32 bytes, 43 characters); a ticket that is not well-formed is the 400 whatever it resembles, and the 403 is a well-formed ticket that no key signs. ticket_cases gain a payload part of each length base64url without padding can have (4n characters, 4n+2 and 4n+3) and one that holds - and _; verify_cases gain the mangled tickets made from them - a newline, a character more or fewer, padding, the standard alphabet, bits left over in a last character, a part missing, empty or added, another version - each with the status it gets. One earlier case changed with the rule: the signature of 'a tampered signature' left bits over in its last character, so it is now tampered in canonical form (403) and its earlier ticket is the case after it (400). Version 4 (one rule for a number, a duration, a switch and a payload). number_cases pin how a value is read as a whole number (whole) and as a duration (duration_ms, in milliseconds), null where it spells none: a whole number is a JSON number with a whole value or ASCII digits, at most 9007199254740991 - the largest whole number both runtimes hold exactly - with the white space both runtimes' trim takes ignored around it and none inside; a duration is such a number of seconds, or such a number and right after it one of ms, s, m, h, d, at most 9007199254740991 milliseconds. The first 101 values are the LLM helper's numbers.probes as they stood when this version was written, with the same verdicts but for the durations between that many milliseconds and that many seconds, which the helper holds in seconds. switch_cases pin a switch: true or false for the boolean and for the text in any letter case, \"default\" for no value and an empty one, null for any other value, which a setting refuses by name. message_cases gain a turn and a ttl in each spelling the rule reads - the event carries the whole number - and in spellings it refuses, and a graph id and a correlation id with a lone surrogate, which no ticket can carry: the exact 400, for an advice too. ticket_cases gain the escapes of the canonical form and the largest numbers. verify_cases gain payloads a key holder signed (their names begin 'signed:'): the signed bytes are the canonical JSON of a wait's five fields or the ticket is malformed - a float for a whole number, a number past 9007199254740991, an escape the canonical form does not write, a key twice, a space, another order of the keys, bytes that are not UTF-8. readvice_cases and reply_cases gain graphs named as members every object has (constructor, toString, __proto__): a graph is one the allowlist names or it is the 404. Version 5 (one reader of a time; an expiry both packs can write; a turn the record holds; blank by one rule; every digit of a number in the record). time_cases pin a time a caller supplies: ms, the instant in milliseconds from 1970-01-01T00:00:00Z, and stamp, the text both packs write for that instant - or null for both where the text is no time. A time is a date YYYY-MM-DD, an upper-case T, a time HH:MM or HH:MM:SS with a fraction of one to nine digits at most, then Z or +HH:MM or -HH:MM, and nothing before or after it: a date the calendar has, hour 0 to 23, minute and second 0 to 59, an offset of at most 23:59, the years 0001 to 9999 as written and in UTC; the instant is read to the millisecond, a longer fraction cut. text_cases pin the white space around a text: trimmed, the text without it, and blank, whether nothing is left - the 24 characters of the number rule and no other, so U+FEFF, U+0085 and U+001C to U+001F are characters of a name. message_cases gain requested_at in the spellings the rule reads - the event keeps it as written, the expiry is written in UTC - and in spellings it refuses; a wait whose expiry is not before the year 10000, the exact 400; an expiry before 1970, whose whole seconds in the ticket are the floor; a turn up to 2147483647, the largest the record's INTEGER column holds, and the 400 past it (the largest turn of version 4 was 9007199254740991); required texts that are blank, and texts of characters that are not white space. transition_cases gain a row whose re-advices and whose sweep write their times in another spelling - at an offset, without the milliseconds: the record orders them by their instants, as the reference store compares two stamps, never by their texts. exact_cases pin a whole number past 9007199254740991 in a waiting call's input and in a decision: numbers gives each as text with the place it stands at, since a JSON number that large is not exact in every reader; record is the text the record's message column is given and decisions_record its decisions column's - compact JSON with every digit, the event's members in the order kind, graph_id, description, correlation_id, turn, node, summary, details, calls, ttl, requested_at, expires_at, ticket, link.", "ticket_cases": [ { "name": "an approval's ticket", @@ -86,6 +86,90 @@ "e": 1795252324 }, "ticket": "v1.eyJjIjoiUTM-UTI_IiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.2LiQLRopPATfnlsnqRn6KdQUuCLCTv5UzQGjbVFdlRI" + }, + { + "name": "a quote and a backslash are escaped", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order \"1002\" \\ case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXIgXCIxMDAyXCIgXFwgY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.GR8d2xz5bNOEa_TUKFGANpAWtfHxPm1b5Or4NF02bqA" + }, + { + "name": "a newline and a tab are their short escapes", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order\n1002\tcase", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXJcbjEwMDJcdGNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.pZlZ_ZnjOBaIDhzCdU3l7Zr_iV4quX42LJ202abpIYM" + }, + { + "name": "another control character is its escape in lower case", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order\u001f1002\u0001case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXJcdTAwMWYxMDAyXHUwMDAxY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.m_GsIvRbWNSIf7ZzqBt8FbezFm-O90Uqp-oB3I3WaMs" + }, + { + "name": "a slash, DEL and the line separators are kept as they are", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order/1002

case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXIvMTAwMn_igKjigKljYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.c9orOPgIZ-_RXuyP0hCRchJ5N0zL87cAvA_kqKnqDcU" + }, + { + "name": "a character beyond the basic plane is kept as its four bytes", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order-𝟟-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXIt8J2fny1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.SVeH87ks-Wy5e-kyrnubiBdjj0u9211szctuBE4gywc" + }, + { + "name": "the largest turn and the largest expiry", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 9007199254740991, + "k": "approval", + "e": 9007199254740991 + }, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6OTAwNzE5OTI1NDc0MDk5MSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjkwMDcxOTkyNTQ3NDA5OTF9.YOygqOmGcUTFzMJXK_t1qSLPeYKxqcFAks2zdUVsGjw" + }, + { + "name": "a turn of zero and an expiry before 1970", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 0, + "k": "approval", + "e": -1 + }, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjowfQ.oGlE32krFfNiMWxa7Ygr8HdE5LH4rqPv-E0vF0A95kw" } ], "verify_cases": [ @@ -868,1474 +952,908 @@ "ticket": "v2.%%%.###", "status": 400, "message": "Ticket version v2 is not supported" - } - ], - "message_cases": [ + }, { - "name": "an approval", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-21T09:12:04.118Z", - "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", - "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + "name": "signed: the canonical payload", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "payload": { + "c": "order-1002-case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 } }, { - "name": "a question (ttl as whole seconds)", - "message": { - "kind": "question", - "graph_id": "plan-assistant", - "description": "Planning assistant: the owner picks a plan", - "correlation_id": "release-42", - "turn": 4, - "summary": "Which plan should the release follow? (A, B, C)", - "calls": [ - { - "id": "toolu_02B", - "name": "ask_owner", - "ask": true, - "wait": true, - "input": { - "question": "Which plan should the release follow?", - "options": [ - "A", - "B", - "C" - ] - } - } - ], - "ttl": 3600, - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "event": { - "kind": "question", - "graph_id": "plan-assistant", - "description": "Planning assistant: the owner picks a plan", - "correlation_id": "release-42", - "turn": 4, - "summary": "Which plan should the release follow? (A, B, C)", - "calls": [ - { - "id": "toolu_02B", - "name": "ask_owner", - "ask": true, - "wait": true, - "input": { - "question": "Which plan should the release follow?", - "options": [ - "A", - "B", - "C" - ] - } - } - ], - "ttl": 3600, - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-19T10:12:04.118Z", - "ticket": "v1.eyJjIjoicmVsZWFzZS00MiIsImUiOjE3OTUwODMxMjQsImciOiJwbGFuLWFzc2lzdGFudCIsImsiOiJxdWVzdGlvbiIsInQiOjR9.yZC3ozsEy46UIquX4_vu7VWETFPpqF-GKlUFXh8AkG0", - "link": "https://ask.example.test/ask/v1.eyJjIjoicmVsZWFzZS00MiIsImUiOjE3OTUwODMxMjQsImciOiJwbGFuLWFzc2lzdGFudCIsImsiOiJxdWVzdGlvbiIsInQiOjR9.yZC3ozsEy46UIquX4_vu7VWETFPpqF-GKlUFXh8AkG0" - } + "name": "signed: not JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.bm90IGpzb24.ROl00bnQzmhac2gP22AzeMfexP9GI2k3O2VTbcPl2a8", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "an advice (no ticket, no link)", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 3, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "event": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 3, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z" - } + "name": "signed: not UTF-8", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.__4A.jslaip2VSlkFPr2NzSIa3g1e9h-bwiMJH1xPT0kBiZY", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "an advice without a turn", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "event": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z" - } + "name": "signed: an empty object", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.e30.-5tNnrDX2FBbAa_APRnOWVYrqmKCSV4RD8631glbTGY", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "a reply url with a trailing slash", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test/", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-21T09:12:04.118Z", - "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", - "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" - } + "name": "signed: a list", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.WzEsMl0.DiKEAHsFCm5kKY15aTArnwLoMPq2pZMSYdG6s2yBODk", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "not a map", - "message": [ - "kind" + "name": "signed: null", + "keys": [ + "test-key-current", + "test-key-previous" ], - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "now": 1795089600, + "ticket": "v1.bnVsbA.06fp24QIKWX6G_jrtUTCgOxGBGjLL3C5FXFs30QUwFU", "status": 400, - "error": "person.ask takes a map" + "message": "Ticket is malformed" }, { - "name": "kind missing", - "message": { - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a string", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.InRleHQi.3UzZEX0R5kTKLEB7gIBlhmYPW2n6Wh5RD-y-Wo9fzVQ", "status": 400, - "error": "kind must be one of approval, question, advice" + "message": "Ticket is malformed" }, { - "name": "kind unknown", - "message": { - "kind": "notice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a number", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.Nw.Lu7WpkxbLGUnBhCMSz7W6xgIPDhjbKnUoytvGn__KTI", "status": 400, - "error": "kind must be one of approval, question, advice" + "message": "Ticket is malformed" }, { - "name": "graph_id missing", - "message": { - "kind": "approval", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: an expiry of NaN", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoieSIsImUiOk5hTiwiZyI6IngiLCJrIjoiYXBwcm92YWwiLCJ0IjoxfQ.yS7IyfOd8Tzr_bjEExb4PMTZcq0scFKp9W_qLSRKMOs", "status": 400, - "error": "graph_id is required" + "message": "Ticket is malformed" }, { - "name": "graph_id blank", - "message": { - "kind": "approval", - "graph_id": " ", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: an expiry of Infinity", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoieSIsImUiOkluZmluaXR5LCJnIjoieCIsImsiOiJhcHByb3ZhbCIsInQiOjF9.aqoKnTCecoiL1bkRtPdA0FT_2cXTASK468Y3cNQdpkM", "status": 400, - "error": "graph_id is required" + "message": "Ticket is malformed" }, { - "name": "description not text", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": 7, - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a byte order mark first", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.77u_eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.KO4I7eeVZ2IqWOHBaznxzx0BB6ZF-ivEDDhHV4816ZA", "status": 400, - "error": "description must be text" + "message": "Ticket is malformed" }, { - "name": "correlation_id missing", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: fifty lists inside one another", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.W1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tdXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXQ.68v26kHOHbqmS8fKkyVY930v2hAq7laEV7RRlv4alWQ", "status": 400, - "error": "correlation_id is required" + "message": "Ticket is malformed" }, { - "name": "summary missing", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a lone surrogate written as an escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItXHVkODAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.k-8bmO6BJxooR0hOMSF2JNeHFw0RsidIitAx-A9PRrQ", "status": 400, - "error": "summary is required" + "message": "Ticket is malformed" }, { - "name": "node not text", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": [ - "assist" - ], - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a character beyond the basic plane written as two escapes", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItXHVkODM1XHVkZmRmLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.wcHeDEQKr2o3A3vwgAecxOw_b-uDsJUBAFrQ7FIBWZM", "status": 400, - "error": "node must be text" + "message": "Ticket is malformed" }, { - "name": "requested_at not a time", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "yesterday" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "status": 400, - "error": "requested_at must be an ISO-8601 time" + "name": "signed: a character beyond the basic plane as its four bytes", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIt8J2fny1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.SVeH87ks-Wy5e-kyrnubiBdjj0u9211szctuBE4gywc", + "payload": { + "c": "order-𝟟-case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } }, { - "name": "turn missing for an approval", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a letter written as an escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItXHUwMDMxMDAyLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.1h5PT3WbXboZOyg06glzBWDzuWyaYzochHhx_snMTHE", "status": 400, - "error": "turn is required for an approval or a question" + "message": "Ticket is malformed" }, { - "name": "turn negative", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": -1, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a slash written as an escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcLzEwMDItY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.bdxQXR-1x85Tj_Pt_7O9ya-bKwr73uARDYKkZJVA4zE", "status": 400, - "error": "turn must be a whole number >= 0" + "message": "Ticket is malformed" }, { - "name": "turn a boolean", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": true, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a slash as it is", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIvMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.C95J7CdTpKHcwwtCmSQXKsEU2yH3sIcye6V13DH5TRU", + "payload": { + "c": "order/1002-case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: a control character as its escape in lower case", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcdTAwMWYxMDAyIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.MgReFMdWicN0x7C9sKHACyuWqWKF7hIGmC6qaEO_od8", + "payload": { + "c": "order\u001f1002", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: a control character as its escape in upper case", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcdTAwMUYxMDAyIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.kTBJ8voi3WZYsd_yH_eX5Qwa_Ng0bnXlr9E0JC8UTb8", "status": 400, - "error": "turn must be a whole number >= 0" + "message": "Ticket is malformed" }, { - "name": "calls empty", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "status": 400, - "error": "calls must be a non-empty list of the waiting calls, each with an id" + "name": "signed: a newline as its short escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcbjEwMDIiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.m-Kg3uK5cl0zYfxwV4RMzS4K3SeQCyuAsMnMi685czQ", + "payload": { + "c": "order\n1002", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } }, { - "name": "a call without an id", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "name": "issue_refund" - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a newline as its long escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcdTAwMGExMDAyIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.QNpa6i5QZVOQi42QnAeEj2HzrrFw4E59OlCtESfBbKQ", "status": 400, - "error": "calls must be a non-empty list of the waiting calls, each with an id" + "message": "Ticket is malformed" }, { - "name": "ttl missing", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a control character as it is", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIfMTAwMiIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.r7uf2ysEz80iPDz5XxkTgr5kjsdiVeyRiEjZzLjmW2o", "status": 400, - "error": "ttl is required for an approval or a question" + "message": "Ticket is malformed" }, { - "name": "ttl not a duration", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "soon", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a quote and a backslash as their escapes", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIgXCIxMDAyXCIgXFwgY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.GR8d2xz5bNOEa_TUKFGANpAWtfHxPm1b5Or4NF02bqA", + "payload": { + "c": "order \"1002\" \\ case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: the line separator as it is", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXLigKgxMDAyIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.8SRh-QxTDqbtwl2J9LlGYOqKGtfp3be4KDiHfpfWIEo", + "payload": { + "c": "order
1002", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: the line separator written as an escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcdTIwMjgxMDAyIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.4A7jLlw5Ot2MSZHy-OZgvGy6uvIBDQwvUAW-xUfQFw4", "status": 400, - "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + "message": "Ticket is malformed" }, { - "name": "ttl zero", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": 0, - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a turn of 2.0", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIuMH0.Buni_FQQuNebaqNHBVQSHsMzZDsYv5taQ4HmjDW2aC0", "status": 400, - "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + "message": "Ticket is malformed" }, { - "name": "an advice with calls", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 3, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ] - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a turn of 2e0", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJlMH0.EXNh7SLEeRdhBB9yLQjXf0ztUSAu7zlts2PW6V_E-jA", "status": 400, - "error": "an advice carries no calls and no ttl" + "message": "Ticket is malformed" }, { - "name": "an advice with a ttl", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 3, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z", - "ttl": "1d" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a turn of -0", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOi0wfQ.t0Z96QA09f7Fs7w8uH-DtdII1SIO_E74azmzcAyiTTg", "status": 400, - "error": "an advice carries no calls and no ttl" + "message": "Ticket is malformed" }, { - "name": "an advice with a negative turn", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": -2, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a turn of -0.0", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOi0wLjB9.Hdzz4MCHHjNRZg2UoSAkximTxKQApZSmXsyH2wG00Bw", "status": 400, - "error": "turn must be a whole number >= 0" + "message": "Ticket is malformed" }, { - "name": "details not text on an advice", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 3, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": { - "text": "x" - }, - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a turn of 2.5", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIuNX0.6hTexIwyTqB87MbblGlZ0g-Y8lAfOFnTuhkQ_lfQZrw", "status": 400, - "error": "details must be text" - } - ], - "readvice_cases": [ + "message": "Ticket is malformed" + }, { - "name": "the re-advice of an approval", + "name": "signed: a turn as text", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOiIyIn0.r9Pr8an7lzVoSbWH5du0ZNGWHN07hTgMkbBPfHgNKsE", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a turn of true", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOnRydWV9.8y1fY5L1tmL8twjGmnj6rlEoEka9JNnMx7FP8RJKGM4", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a turn of -1", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOi0xfQ.t_5U9OvYP8MS3k8FsnQviJTWvzxjOAHIGxyYn_CFWNI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a turn of 02", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjAyfQ.eFi-AAL7j8W0VAas-WShkqNMQEhmNK1Bg9xRWRA-ms0", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a turn of +2", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOisyfQ.rqre1Dj1d0n3BtqPZAu6sPeXRQCi-OmmisxtO0qBtqE", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a turn of zero", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjB9.qDSpHhw2iNBRnIgDQKYhTm9tt4y8w6mgyi6jE8n751U", "payload": { - "g": "order-assistant", "c": "order-1002-case", - "t": 2, + "e": 1795252324, + "g": "order-assistant", "k": "approval", - "e": 1795252324 - }, - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/order-assistant", - "headers": { - "x-correlation-id": "order-1002-case" - }, - "body": { - "turn": 2 - } + "t": 0 } }, { - "name": "a graph that is not in the allowlist", + "name": "signed: the largest turn", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjkwMDcxOTkyNTQ3NDA5OTF9.x4rtsZ8qc79zrxBWmhePxTuWzdHLRcL-QmrCe8q6oEY", "payload": { - "g": "other-graph", "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "status": 404, - "error": "graph other-graph is not configured for replies" - } - ], - "reply_cases": [ - { - "name": "an approval with a note", - "payload": { + "e": 1795252324, "g": "order-assistant", - "c": "order-1002-case", - "t": 2, "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "Carrier confirmed the loss" - } - ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/order-assistant", - "headers": { - "x-correlation-id": "order-1002-case" - }, - "body": { - "turn": 2, - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "[operator-17 at 2026-11-19T10:00:00.000Z] Carrier confirmed the loss" - } - ] - } + "t": 9007199254740991 } }, { - "name": "a refusal without a note", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": false - } + "name": "signed: a turn one past the largest", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/order-assistant", - "headers": { - "x-correlation-id": "order-1002-case" - }, - "body": { - "turn": 2, - "decisions": [ - { - "id": "toolu_01A", - "approved": false, - "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" - } - ] - } - } + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjkwMDcxOTkyNTQ3NDA5OTJ9.kxCAfBasWDD3pkc6H8SszyX_j7BPRWbEpsEF49Y_vCY", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "a refusal with an empty note", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": false, - "note": "" - } + "name": "signed: a turn two past the largest", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/order-assistant", - "headers": { - "x-correlation-id": "order-1002-case" - }, - "body": { - "turn": 2, - "decisions": [ - { - "id": "toolu_01A", - "approved": false, - "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" - } - ] - } - } + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjkwMDcxOTkyNTQ3NDA5OTN9.QoYoVLDFCdZ86w9p64eM3blS72R6lCeCse70LKZTzRM", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "a question's answer travels unchanged", - "payload": { - "g": "plan-assistant", - "c": "release-42", - "t": 4, - "k": "question", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_02B", - "answer": "B" - } + "name": "signed: a turn of 1e400", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/plan-assistant", - "headers": { - "x-correlation-id": "release-42" - }, - "body": { - "turn": 4, - "decisions": [ - { - "id": "toolu_02B", - "answer": "B" - } - ] - } - } + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjFlNDAwfQ.U9WDcaPnmUuREFVHV8aqb8z3mXbiIg8cZZu8RRp-ae4", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "a question's answer may be any JSON value", - "payload": { - "g": "plan-assistant", - "c": "release-42", - "t": 4, - "k": "question", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_02B", - "answer": { - "plan": "B", - "why": "cheaper" - } - } + "name": "signed: an expiry as a float", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/plan-assistant", - "headers": { - "x-correlation-id": "release-42" - }, - "body": { - "turn": 4, - "decisions": [ - { - "id": "toolu_02B", - "answer": { - "plan": "B", - "why": "cheaper" - } - } - ] - } - } + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNC4wLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.VlujmHfAxLXNRRJnHQOkogwuC6aFOoViVmNfdm2GnxE", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "a turn with a tool call and a question", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": true - }, - { - "id": "toolu_02B", - "answer": "A" - } + "name": "signed: an expiry with a fraction", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/order-assistant", - "headers": { - "x-correlation-id": "order-1002-case" - }, - "body": { - "turn": 2, - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" - }, - { - "id": "toolu_02B", - "answer": "A" - } - ] - } - } - }, - { - "name": "decisions empty", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MS43OTUyNTIzMjQ1ZTksImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ._4-4WTxVVVvW41JW9bztvzacZ1sKTF_wIQbX77cLPyc", "status": 400, - "error": "decisions must be a non-empty list, one per waiting call" + "message": "Ticket is malformed" }, { - "name": "decisions not a list", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": { - "id": "toolu_01A", - "approved": true - }, - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "name": "signed: an expiry of 1e400", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MWU0MDAsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.CsPmH8fzZwR9ZmGTeE73v0d1AGiR96m53RGdNsha-r8", "status": 400, - "error": "decisions must be a non-empty list, one per waiting call" + "message": "Ticket is malformed" }, { - "name": "a decision without an id", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "approved": true - } + "name": "signed: an expiry of 2^63", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6OTIyMzM3MjAzNjg1NDc3NTgwOCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.OTqB4M-8N37lVBEE-Ih3Ck3qsSoWfuL3--MwyoXdh5I", "status": 400, - "error": "each decision needs the id of its call" + "message": "Ticket is malformed" }, { - "name": "a decision with approved and answer", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "answer": "x" - } + "name": "signed: an expiry as text", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6IjE3OTUyNTIzMjQiLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Zjvz7EDRmcXbOYO_CLwZb-P20Kb9EBkPLBu0kivWCgI", "status": 400, - "error": "each decision carries approved (with an optional note) or answer, not both" + "message": "Ticket is malformed" }, { - "name": "a decision with neither", + "name": "signed: the largest expiry", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6OTAwNzE5OTI1NDc0MDk5MSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.AWE1LPsfSWCa1dDJyCjnMPXSqkd-QNKxGJHmb_G8cNc", "payload": { - "g": "order-assistant", "c": "order-1002-case", - "t": 2, + "e": 9007199254740991, + "g": "order-assistant", "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "note": "x" - } - ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "status": 400, - "error": "each decision carries approved (with an optional note) or answer" + "t": 2 + } }, { - "name": "approved not a boolean", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": "yes" - } + "name": "signed: an expiry one past the largest", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6OTAwNzE5OTI1NDc0MDk5MiwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.yBLFHRodxObWt3skCvW9wWjO6Xj38BEeGl4Innh915c", "status": 400, - "error": "approved must be true or false" + "message": "Ticket is malformed" }, { - "name": "note not text", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": 5 - } + "name": "signed: an expiry before 1970", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "status": 400, - "error": "note must be text" + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.wBOW5_f_KTnMKg_TLXgDjegSEr4ZRVy2A7xF6O8sxSM", + "status": 410, + "message": "Ticket expired" }, { - "name": "an answer with a note", - "payload": { - "g": "plan-assistant", - "c": "release-42", - "t": 4, - "k": "question", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_02B", - "answer": "B", - "note": "x" - } + "name": "signed: the smallest expiry", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTkwMDcxOTkyNTQ3NDA5OTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.qbuNc20XwqIFfnyjYZMI2FOY1kqiw2dbJgIk1YaZm2A", + "status": 410, + "message": "Ticket expired" + }, + { + "name": "signed: an expiry one before the smallest", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTkwMDcxOTkyNTQ3NDA5OTIsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.t6TnZlsjLDfISHMFr1IEgl9MfLCc5WJqQqRpeCmSBFg", "status": 400, - "error": "a question's decision carries an answer and no note" + "message": "Ticket is malformed" }, { - "name": "a graph that is not in the allowlist", - "payload": { - "g": "other-graph", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": true - } + "name": "signed: a key twice", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "status": 404, - "error": "graph other-graph is not configured for replies" - } - ], - "outcome_cases": [ + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im90aGVyIiwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.1nHPP2jJqHIH_5l-hFKy9fpZTz-fzCg-ymmQiVYBdqw", + "status": 400, + "message": "Ticket is malformed" + }, { - "name": "the graph answered", - "engine": { - "status": 200, - "body": "{\"type\": \"answer\", \"turn\": 3, \"run\": \"resume\", \"message\": \"Your refund has been issued.\"}", - "error": null - }, - "status": 200, - "body": { - "type": "answer", - "turn": 3, - "run": "resume", - "message": "Your refund has been issued." - } + "name": "signed: the same member twice", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIsInQiOjJ9.2M42UaCQBQSKj2A5sQV4bzPSfK-1qPNwvHQzDINDBOE", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the model asked again", - "engine": { - "status": 200, - "body": "{\"type\": \"approval\", \"turn\": 4, \"calls\": []}", - "error": null - }, - "status": 200, - "body": { - "type": "approval", - "turn": 4, - "calls": [] - } + "name": "signed: spaces in the JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjogIm9yZGVyLTEwMDItY2FzZSIsICJlIjogMTc5NTI1MjMyNCwgImciOiAib3JkZXItYXNzaXN0YW50IiwgImsiOiAiYXBwcm92YWwiLCAidCI6IDJ9.cA3ehwKiJDWNXXY5ne1-tIOR9cASyGzkX3UQF3c6lEw", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "nothing waiting (the gate)", - "engine": { - "status": 410, - "body": "{\"type\": \"nothing-waiting\"}", - "error": null - }, - "status": 410, - "body": { - "type": "nothing-waiting" - } + "name": "signed: the keys in the order the issuer was given", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJnIjoib3JkZXItYXNzaXN0YW50IiwiYyI6Im9yZGVyLTEwMDItY2FzZSIsInQiOjIsImsiOiJhcHByb3ZhbCIsImUiOjE3OTUyNTIzMjR9.ch6DP8ypFCC8mmqOlFvXpxxmteDiTPn7jBzP1BztXBQ", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph refused the decisions", - "engine": { - "status": 400, - "body": "{\"type\": \"error\", \"message\": \"unknown call id\"}", - "error": null - }, + "name": "signed: a newline after the JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9Cg.d4fIk4wBrIoB5ryV5IeKjrkwlIpDFrgQ5Eibuh9xYoA", "status": 400, - "body": { - "type": "error", - "message": "unknown call id" - } + "message": "Ticket is malformed" }, { - "name": "the graph failed", - "engine": { - "status": 500, - "body": "{\"type\": \"error\", \"message\": \"boom\"}", - "error": null - }, - "status": 500, - "body": { - "type": "error", - "message": "boom" - } + "name": "signed: a space before the JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.IHsiYyI6Im9yZGVyLTEwMDItY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.MlU6vRYBN36ku7vez4bG9VHcZatTKBT93MvewHvtIHw", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph answered text", - "engine": { - "status": 200, - "body": "OK", - "error": null - }, - "status": 502, - "body": { - "type": "error", - "message": "the graph answered outside the contract" - } + "name": "signed: a NUL after the JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9AA.6IfmZmO88QqddIjFJJQly51s3mwyAQXKc-r-sz42e50", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph answered a JSON list", - "engine": { - "status": 200, - "body": "[1,2]", - "error": null - }, - "status": 502, - "body": { - "type": "error", - "message": "the graph answered outside the contract" - } + "name": "signed: text after the JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9IHg.brgUNDGy0f_GfxNACVKcUonrwxmvVx6-ZxMU0P9AwQ4", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph answered nothing", - "engine": { - "status": 200, - "body": "", - "error": null - }, - "status": 502, - "body": { - "type": "error", - "message": "the graph answered outside the contract" - } + "name": "signed: a byte that is not UTF-8 in the correlation id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIt_y1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.Isq6uRxWMQUHh_wUVwyfqfZdfc2xZHeQv36szG-MMNU", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph did not answer", - "engine": { - "status": null, - "body": null, - "error": "ClientConnectorError" - }, - "status": 502, - "body": { - "type": "error", - "message": "the graph did not answer - ClientConnectorError" - } + "name": "signed: an overlong slash in the correlation id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItwK8tY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.BKZ6c78UWw1imOM0tV8c-07BLVuGmt0m7rJRIrt1n1I", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph timed out", - "engine": { - "status": null, - "body": null, - "error": "TimeoutError" - }, - "status": 502, - "body": { - "type": "error", - "message": "the graph did not answer - TimeoutError" + "name": "signed: a surrogate half as three bytes in the correlation id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIt7aCALWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.TxYuW2Zuydc9sTegMsfH0EYTUfri9mibELSAHUgHYPA", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: the replacement character in the correlation id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIt77-9LWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.i6SKozUKCKr5H-DeWlkMdYMn8AqbaetlD_pxV6RPlvw", + "payload": { + "c": "order-�-case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: an extra key", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIsIngiOjF9.CJtL4wrVaExlaCLG66DzT0DL6k-qmvnVG9Nk3v80OYg", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a key missing", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.lWEUB06BXS-lYJDXzOl31Xq9Gl3bT2Obx2VxvLAsjD0", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: the kind of an advice", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhZHZpY2UiLCJ0IjoyfQ.pDBtatNmV76BvYBM675o4UpACrpJTVGIzVwxSfJGxHw", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: an empty graph id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IiIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.FNSX-0tn7JKahBhdJ8EaBK_ST3OWkBoTnwgLuqo3W00", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: an empty correlation id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoiIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.Clib_tF9GX0vi1AR5gr5tdqbhL7IxyBbniaFFFmZ4U4", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a graph id of one space", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IiAiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.HJbo3PavPatcne6hF596ML5Aj9Ng1LL-8EfRKnqGcFU", + "payload": { + "c": "order-1002-case", + "e": 1795252324, + "g": " ", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: __proto__ as a key", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIsIl9fcHJvdG9fXyI6eyJ4IjoxfX0.MQc0qp-_GyyKFLzs15YtnrCx8YrMyYlP51VNoLKjMes", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a graph named __proto__", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Il9fcHJvdG9fXyIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.V5QoTy4aXCZwu6aoWLUgrFioYX8Q5ULOj84eaeouRBs", + "payload": { + "c": "order-1002-case", + "e": 1795252324, + "g": "__proto__", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: a graph named constructor", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6ImNvbnN0cnVjdG9yIiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.f-jwzRiwY2Ub2g1wSfxUk3wfxgp2dqvNnzOXOdjj3o4", + "payload": { + "c": "order-1002-case", + "e": 1795252324, + "g": "constructor", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: a question", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJxdWVzdGlvbiIsInQiOjJ9.ZfNIavj-5ybPN3JaMXwtI3DMDkPsoD2v4qoCPc-86dI", + "payload": { + "c": "order-1002-case", + "e": 1795252324, + "g": "order-assistant", + "k": "question", + "t": 2 } + }, + { + "name": "signed: a turn of 2.0 under the previous key", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIuMH0.KnsTR1e3Bv5HE14J9TToWAZ2jjrZihcUSD8o3nbx0AY", + "status": 400, + "message": "Ticket is malformed" } ], - "record_cases": [ + "message_cases": [ { "name": "an approval", - "event": { + "message": { "kind": "approval", "graph_id": "order-assistant", "description": "Customer-support assistant: a refund waits for a supervisor", "correlation_id": "order-1002-case", "turn": 2, "node": "assist", - "summary": "A refund waits for the supervisor's decision", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", "calls": [ { "id": "toolu_01A", @@ -2350,74 +1868,47 @@ } ], "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-21T09:12:04.118Z", - "ticket": "v1.payload.mac", - "link": "https://ask.example.test/ask/v1.payload.mac" + "requested_at": "2026-11-19T09:12:04.118Z" }, - "now": "2026-11-19T09:12:05.000Z", - "key": [ - "order-assistant", - "order-1002-case", - 2 - ], - "row": { + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { "kind": "approval", "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", "correlation_id": "order-1002-case", "turn": 2, - "ticket": "v1.payload.mac", - "link": "https://ask.example.test/ask/v1.payload.mac", - "description": "Customer-support assistant: a refund waits for a supervisor", - "summary": "A refund waits for the supervisor's decision", - "details": null, - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-21T09:12:04.118Z", - "ticket": "v1.payload.mac", - "link": "https://ask.example.test/ask/v1.payload.mac" - }, - "state": "open", + } + ], + "ttl": "2d", "requested_at": "2026-11-19T09:12:04.118Z", "expires_at": "2026-11-21T09:12:04.118Z", - "updated_at": "2026-11-19T09:12:05.000Z", - "answered_at": null, - "answered_by": null, - "decisions": null, - "outcome": null + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" } }, { - "name": "a question", - "event": { + "name": "a question (ttl as whole seconds)", + "message": { "kind": "question", "graph_id": "plan-assistant", - "description": "Planning assistant: the owner picks one of the plans", + "description": "Planning assistant: the owner picks a plan", "correlation_id": "release-42", - "turn": 1, - "node": "plan", - "summary": "The planning assistant asks which plan to follow", + "turn": 4, + "summary": "Which plan should the release follow? (A, B, C)", "calls": [ { "id": "toolu_02B", @@ -2425,7 +1916,7 @@ "ask": true, "wait": true, "input": { - "question": "Which plan?", + "question": "Which plan should the release follow?", "options": [ "A", "B", @@ -2435,905 +1926,10030 @@ } ], "ttl": 3600, - "requested_at": "2026-11-19T09:20:00.000Z", - "expires_at": "2026-11-19T10:20:00.000Z", - "ticket": "v1.plan.mac", - "link": "https://ask.example.test/ask/v1.plan.mac" + "requested_at": "2026-11-19T09:12:04.118Z" }, - "now": "2026-11-19T09:12:05.000Z", - "key": [ - "plan-assistant", - "release-42", - 1 - ], - "row": { + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { "kind": "question", "graph_id": "plan-assistant", + "description": "Planning assistant: the owner picks a plan", "correlation_id": "release-42", - "turn": 1, - "ticket": "v1.plan.mac", - "link": "https://ask.example.test/ask/v1.plan.mac", - "description": "Planning assistant: the owner picks one of the plans", - "summary": "The planning assistant asks which plan to follow", - "details": null, - "message": { - "kind": "question", - "graph_id": "plan-assistant", - "description": "Planning assistant: the owner picks one of the plans", - "correlation_id": "release-42", - "turn": 1, - "node": "plan", - "summary": "The planning assistant asks which plan to follow", - "calls": [ - { - "id": "toolu_02B", - "name": "ask_owner", - "ask": true, - "wait": true, - "input": { - "question": "Which plan?", - "options": [ - "A", - "B", - "C" - ] - } + "turn": 4, + "summary": "Which plan should the release follow? (A, B, C)", + "calls": [ + { + "id": "toolu_02B", + "name": "ask_owner", + "ask": true, + "wait": true, + "input": { + "question": "Which plan should the release follow?", + "options": [ + "A", + "B", + "C" + ] } - ], - "ttl": 3600, - "requested_at": "2026-11-19T09:20:00.000Z", - "expires_at": "2026-11-19T10:20:00.000Z", - "ticket": "v1.plan.mac", - "link": "https://ask.example.test/ask/v1.plan.mac" - }, - "state": "open", - "requested_at": "2026-11-19T09:20:00.000Z", - "expires_at": "2026-11-19T10:20:00.000Z", - "updated_at": "2026-11-19T09:12:05.000Z", - "answered_at": null, - "answered_by": null, - "decisions": null, - "outcome": null + } + ], + "ttl": 3600, + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-19T10:12:04.118Z", + "ticket": "v1.eyJjIjoicmVsZWFzZS00MiIsImUiOjE3OTUwODMxMjQsImciOiJwbGFuLWFzc2lzdGFudCIsImsiOiJxdWVzdGlvbiIsInQiOjR9.yZC3ozsEy46UIquX4_vu7VWETFPpqF-GKlUFXh8AkG0", + "link": "https://ask.example.test/ask/v1.eyJjIjoicmVsZWFzZS00MiIsImUiOjE3OTUwODMxMjQsImciOiJwbGFuLWFzc2lzdGFudCIsImsiOiJxdWVzdGlvbiIsInQiOjR9.yZC3ozsEy46UIquX4_vu7VWETFPpqF-GKlUFXh8AkG0" } }, { - "name": "an advice with a turn", - "event": { + "name": "an advice (no ticket, no link)", + "message": { "kind": "advice", "graph_id": "order-assistant", "description": "Customer-support assistant: a refund waits for a supervisor", "correlation_id": "order-1002-case", - "turn": 2, - "node": "decide", - "summary": "The supervisor's decision was received; the assistant continues", - "details": "The assistant runs the decided call and answers the customer", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", "requested_at": "2026-11-19T09:40:12.004Z" }, - "now": "2026-11-19T09:12:05.000Z", - "key": null, - "row": { + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { "kind": "advice", "graph_id": "order-assistant", - "correlation_id": "order-1002-case", - "turn": 2, - "ticket": null, - "link": null, "description": "Customer-support assistant: a refund waits for a supervisor", - "summary": "The supervisor's decision was received; the assistant continues", - "details": "The assistant runs the decided call and answers the customer", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "decide", - "summary": "The supervisor's decision was received; the assistant continues", - "details": "The assistant runs the decided call and answers the customer", - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "state": null, - "requested_at": "2026-11-19T09:40:12.004Z", - "expires_at": null, - "updated_at": "2026-11-19T09:12:05.000Z", - "answered_at": null, - "answered_by": null, - "decisions": null, - "outcome": null + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" } }, { - "name": "an advice without a turn or a requested_at takes now", - "event": { + "name": "an advice without a turn", + "message": { "kind": "advice", "graph_id": "order-assistant", - "description": "Customer-support assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", "correlation_id": "order-1002-case", - "summary": "Nightly: the queue is empty" + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" }, - "now": "2026-11-19T09:12:05.000Z", - "key": null, - "row": { + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { "kind": "advice", "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", "correlation_id": "order-1002-case", - "turn": null, - "ticket": null, - "link": null, - "description": "Customer-support assistant", - "summary": "Nightly: the queue is empty", - "details": null, - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant", - "correlation_id": "order-1002-case", - "summary": "Nightly: the queue is empty" - }, - "state": null, - "requested_at": "2026-11-19T09:12:05.000Z", - "expires_at": null, - "updated_at": "2026-11-19T09:12:05.000Z", - "answered_at": null, - "answered_by": null, - "decisions": null, - "outcome": null + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" } - } - ], - "answer_cases": [ - { - "name": "the engine answered", - "status": 200, - "body": { - "type": "answer", - "turn": 3, - "message": "Your refund has been issued." - }, - "state": "answered" - }, - { - "name": "the model asked again", - "status": 200, - "body": { - "type": "approval", - "turn": 4, - "calls": [] - }, - "state": "answered" }, { - "name": "the loop refused the decision - the graph re-advised with the error", - "status": 200, - "body": { - "type": "approval", + "name": "a reply url with a trailing slash", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", "turn": 2, - "error": "not a call waiting for approval" - }, - "state": "open" - }, - { - "name": "nothing waiting by status", - "status": 410, - "body": { - "type": "nothing-waiting" + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" }, - "state": "expired" + "key": "test-key-current", + "reply_url": "https://ask.example.test/", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } }, { - "name": "nothing waiting by type", - "status": 200, - "body": { - "type": "nothing-waiting" - }, - "state": "expired" + "name": "not a map", + "message": [ + "kind" + ], + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "person.ask takes a map" }, { - "name": "the ticket expired at the reply endpoint", - "status": 410, - "body": { - "type": "expired", - "message": "Ticket expired" + "name": "kind missing", + "message": { + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" }, - "state": "expired" + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "kind must be one of approval, question, advice" }, { - "name": "the reply endpoint refused the decisions", + "name": "kind unknown", + "message": { + "kind": "notice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", "status": 400, - "body": { - "type": "error", - "message": "each decision needs the id of its call" + "error": "kind must be one of approval, question, advice" + }, + { + "name": "graph_id missing", + "message": { + "kind": "approval", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" }, - "state": "open" + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "graph_id is required" }, { - "name": "the graph did not answer", - "status": 502, - "body": { - "type": "error", - "message": "the graph did not answer - TimeoutError" + "name": "graph_id blank", + "message": { + "kind": "approval", + "graph_id": " ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" }, - "state": "open" + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "graph_id is required" }, { - "name": "the reply endpoint did not answer", - "status": 502, - "body": { - "type": "error", - "message": "the reply endpoint did not answer - ClientConnectorError" + "name": "description not text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": 7, + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" }, - "state": "open" + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "description must be text" }, { - "name": "an answer with no body", - "status": 200, - "body": null, - "state": "answered" - } - ], - "transition_cases": [ + "name": "correlation_id missing", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "correlation_id is required" + }, { - "name": "the reference sequence", - "steps": [ - { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-21T09:12:04.118Z", - "ticket": "v1.payload.mac", - "link": "https://ask.example.test/ask/v1.payload.mac" - }, - "now": "2026-11-19T09:12:05.000Z" - }, - { - "op": "record", - "event": { - "kind": "question", - "graph_id": "plan-assistant", - "description": "Planning assistant: the owner picks one of the plans", - "correlation_id": "release-42", - "turn": 1, - "node": "plan", - "summary": "The planning assistant asks which plan to follow", - "calls": [ - { - "id": "toolu_02B", - "name": "ask_owner", - "ask": true, - "wait": true, - "input": { - "question": "Which plan?", - "options": [ - "A", - "B", - "C" - ] - } - } - ], - "ttl": 3600, - "requested_at": "2026-11-19T09:20:00.000Z", - "expires_at": "2026-11-19T10:20:00.000Z", - "ticket": "v1.plan.mac", - "link": "https://ask.example.test/ask/v1.plan.mac" - }, - "now": "2026-11-19T09:20:01.000Z" - }, - { - "op": "record", - "event": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant", - "correlation_id": "order-1002-case", - "summary": "Nightly: the queue is empty" - }, - "now": "2026-11-19T09:30:00.000Z" - }, - { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:35:00.000Z", - "expires_at": "2026-11-21T09:35:00.000Z", - "ticket": "v1.payload2.mac", - "link": "https://ask.example.test/ask/v1.payload2.mac" - }, - "now": "2026-11-19T09:35:00.500Z", - "note": "a re-advice for the same turn updates the same row with the new ticket" - }, - { - "op": "answer", - "key": [ - "order-assistant", - "order-1002-case", - 2 - ], - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "Carrier confirmed" - } - ], - "who": "operator-17", - "status": 200, - "body": { - "type": "answer", - "turn": 3 - }, - "now": "2026-11-19T09:40:00.000Z" - }, - { - "op": "record", - "event": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "decide", - "summary": "The supervisor's decision was received; the assistant continues", - "details": "The assistant runs the decided call and answers the customer", - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "now": "2026-11-19T09:40:12.100Z" - }, - { - "op": "expire", - "now": "2026-11-19T10:30:00.000Z", - "note": "the question's hour is over; the answered wait is untouched" - }, - { - "op": "since", - "seq": 4, - "limit": 10 - }, - { - "op": "since", - "seq": 0, - "limit": 3 - } - ], - "results": [ - { - "id": 1, - "seq": 1, - "state": "open", - "ticket": "v1.payload.mac" - }, - { - "id": 2, - "seq": 2, - "state": "open", - "ticket": "v1.plan.mac" - }, - { - "id": 3, - "seq": 3, - "state": null, - "ticket": null - }, - { - "id": 1, - "seq": 4, - "state": "open", - "ticket": "v1.payload2.mac" - }, - { - "id": 1, - "seq": 5, - "state": "answered", - "answered_by": "operator-17" - }, - { - "id": 4, - "seq": 6, - "state": null, - "ticket": null - }, - { - "expired": [ - { - "id": 2, - "seq": 7 - } - ] - }, - { - "ids": [ - 1, - 4, - 2 - ], - "seqs": [ - 5, - 6, - 7 - ] - }, - { - "ids": [ - 3, - 1, - 4 - ], - "seqs": [ - 3, - 5, - 6 - ] - } - ], - "final": [ - { - "id": 1, - "seq": 5, - "kind": "approval", - "state": "answered", - "ticket": "v1.payload2.mac", - "turn": 2, - "requested_at": "2026-11-19T09:35:00.000Z", - "expires_at": "2026-11-21T09:35:00.000Z", - "updated_at": "2026-11-19T09:40:00.000Z", - "answered_by": "operator-17", - "outcome": { - "status": 200, - "body": { - "type": "answer", - "turn": 3 + "name": "summary missing", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" } } - }, - { - "id": 2, - "seq": 7, - "kind": "question", - "state": "expired", - "ticket": "v1.plan.mac", - "turn": 1, - "requested_at": "2026-11-19T09:20:00.000Z", - "expires_at": "2026-11-19T10:20:00.000Z", - "updated_at": "2026-11-19T10:30:00.000Z", - "answered_by": null, - "outcome": null - }, - { - "id": 3, - "seq": 3, - "kind": "advice", - "state": null, - "ticket": null, - "turn": null, - "requested_at": "2026-11-19T09:30:00.000Z", - "expires_at": null, - "updated_at": "2026-11-19T09:30:00.000Z", - "answered_by": null, - "outcome": null - }, - { - "id": 4, - "seq": 6, - "kind": "advice", - "state": null, - "ticket": null, - "turn": 2, - "requested_at": "2026-11-19T09:40:12.004Z", - "expires_at": null, - "updated_at": "2026-11-19T09:40:12.100Z", - "answered_by": null, - "outcome": null - } - ] + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "summary is required" }, { - "name": "two devices on one card - the first accepted decision stands", - "steps": [ - { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1004-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1004", - "amount": 240.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T10:00:00.000Z", - "expires_at": "2026-11-21T10:00:00.000Z", - "ticket": "v1.two.mac", - "link": "https://ask.example.test/ask/v1.two.mac" - }, - "now": "2026-11-19T10:00:00.200Z" - }, - { - "op": "answer", - "key": [ - "order-assistant", - "order-1004-case", - 2 - ], - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "from device-2" - } - ], - "who": "device-2", - "status": 410, - "body": { - "type": "nothing-waiting", - "run": "fresh" - }, - "now": "2026-11-19T10:00:01.000Z", - "note": "two devices clicked at once; the engine took the other one's decision, so this one got nothing-waiting, and it lands first: the open row turns expired for a moment" - }, - { - "op": "answer", - "key": [ - "order-assistant", - "order-1004-case", - 2 - ], - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "from device-1" + "name": "node not text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": [ + "assist" + ], + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" } - ], - "who": "device-1", - "status": 200, - "body": { - "type": "answer", - "turn": 3 - }, - "now": "2026-11-19T10:00:02.000Z", - "note": "the accepted decision always wins the row" - }, - { - "op": "answer", - "key": [ - "order-assistant", - "order-1004-case", - 2 - ], - "decisions": [ - { - "id": "toolu_01A", - "approved": false + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "node must be text" + }, + { + "name": "requested_at not a time", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" } - ], - "who": "device-3", - "status": 410, - "body": { - "type": "nothing-waiting", - "run": "fresh" - }, - "now": "2026-11-19T10:00:03.000Z", - "note": "a nothing-waiting after the acceptance changes nothing: the row stands as device-1 left it and the sequence does not move" - }, - { - "op": "since", - "seq": 0, - "limit": 10 - } - ], - "results": [ - { - "id": 1, - "seq": 1, - "state": "open", - "ticket": "v1.two.mac" - }, - { - "id": 1, - "seq": 2, - "state": "expired", - "answered_by": "device-2" - }, - { - "id": 1, - "seq": 3, - "state": "answered", - "answered_by": "device-1" - }, - { - "id": 1, - "seq": 3, - "state": "answered", - "answered_by": "device-1" - }, - { - "ids": [ - 1 - ], - "seqs": [ - 3 - ] - } - ], - "final": [ - { - "id": 1, - "seq": 3, - "kind": "approval", - "state": "answered", - "ticket": "v1.two.mac", - "turn": 2, - "requested_at": "2026-11-19T10:00:00.000Z", - "expires_at": "2026-11-21T10:00:00.000Z", - "updated_at": "2026-11-19T10:00:02.000Z", - "answered_by": "device-1", - "outcome": { - "status": 200, - "body": { - "type": "answer", - "turn": 3 + } + ], + "ttl": "2d", + "requested_at": "yesterday" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "turn missing for an approval", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" } } - } - ] + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "turn is required for an approval or a question" + }, + { + "name": "turn negative", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": -1, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "turn a boolean", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": true, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "calls empty", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "calls must be a non-empty list of the waiting calls, each with an id" + }, + { + "name": "a call without an id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "name": "issue_refund" + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "calls must be a non-empty list of the waiting calls, each with an id" + }, + { + "name": "ttl missing", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "ttl is required for an approval or a question" + }, + { + "name": "ttl not a duration", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "soon", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl zero", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 0, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "an advice with calls", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ] + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "an advice carries no calls and no ttl" + }, + { + "name": "an advice with a ttl", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z", + "ttl": "1d" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "an advice carries no calls and no ttl" + }, + { + "name": "an advice with a negative turn", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": -2, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "details not text on an advice", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": { + "text": "x" + }, + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "details must be text" + }, + { + "name": "a turn written as a float with a whole value is that turn", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2.0, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "a turn written in ASCII digits is that turn", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "a turn with white space around its digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "\t2 ", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "a turn with leading zeros", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "007", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 7, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjd9.n3D1IXY2zZtLLTXz5e69oLXIs7p01zKd6vmYDNCtZTM", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjd9.n3D1IXY2zZtLLTXz5e69oLXIs7p01zKd6vmYDNCtZTM" + } + }, + { + "name": "a turn of zero", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 0, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 0, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjB9.qDSpHhw2iNBRnIgDQKYhTm9tt4y8w6mgyi6jE8n751U", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjB9.qDSpHhw2iNBRnIgDQKYhTm9tt4y8w6mgyi6jE8n751U" + } + }, + { + "name": "a turn of negative zero is turn zero", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": -0.0, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 0, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjB9.qDSpHhw2iNBRnIgDQKYhTm9tt4y8w6mgyi6jE8n751U", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjB9.qDSpHhw2iNBRnIgDQKYhTm9tt4y8w6mgyi6jE8n751U" + } + }, + { + "name": "the largest turn", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483647, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2147483647, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc" + } + }, + { + "name": "an advice's turn written in ASCII digits", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "3", + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z", + "turn": 3 + } + }, + { + "name": "a turn one past the largest", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483648, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a fraction", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2.5, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn in Arabic-Indic digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "٢", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn in fullwidth digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a plus sign", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "+2", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a point in text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2.0", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with an exponent in text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2e0", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with an underscore", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "1_0", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of empty text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn in a list", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": [ + 2 + ], + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "an advice's turn with a fraction", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3.5, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "ttl a float with a whole value is those seconds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 3600.0, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": 3600, + "expires_at": "2026-11-19T10:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA4MzEyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.hP13VNMw6wipQhNjuqvPk2XOIEeUvx66QRtglEUEt9Y", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA4MzEyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.hP13VNMw6wipQhNjuqvPk2XOIEeUvx66QRtglEUEt9Y" + } + }, + { + "name": "ttl in milliseconds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1500ms", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "1500ms", + "expires_at": "2026-11-19T09:12:05.618Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTUyNSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.mscwVj1WR1Vzfn7XbyheoHpIq8BqsVRpHL5v_e4J_tA", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTUyNSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.mscwVj1WR1Vzfn7XbyheoHpIq8BqsVRpHL5v_e4J_tA" + } + }, + { + "name": "ttl with white space around it", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": " 2d\n", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": " 2d\n", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "ttl in ASCII digits without a unit", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "90", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "90", + "expires_at": "2026-11-19T09:13:34.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTYxNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.l-52oTdrGHesgLlKmDRY8rALzWHSnIG06kgHJQPWdo0", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTYxNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.l-52oTdrGHesgLlKmDRY8rALzWHSnIG06kgHJQPWdo0" + } + }, + { + "name": "ttl with leading zeros", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "007m", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "007m", + "expires_at": "2026-11-19T09:19:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTk0NCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.fxl992NeeZ9zR0_gNhs_aXXKac3-yE1Y0bXg-HD6SHw", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTk0NCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.fxl992NeeZ9zR0_gNhs_aXXKac3-yE1Y0bXg-HD6SHw" + } + }, + { + "name": "ttl with a space before its unit", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2 d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl in Arabic-Indic digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "٣m", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl in fullwidth digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "3m", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl with a fraction", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1.5, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl with a fraction and a unit", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1.5h", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl in an upper-case unit", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2D", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl of zero as a float", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 0.0, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl of zero days", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "0d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl negative", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": -5, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl a boolean", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": true, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl one second past the most milliseconds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "9007199254741s", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl one past the largest whole number", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 9007199254740992, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl of four hundred digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "a character beyond the basic plane in the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-𝟟-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-𝟟-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXIt8J2fny1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.SVeH87ks-Wy5e-kyrnubiBdjj0u9211szctuBE4gywc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXIt8J2fny1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.SVeH87ks-Wy5e-kyrnubiBdjj0u9211szctuBE4gywc" + } + }, + { + "name": "a quote, a backslash and a newline in the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order \"1002\" \\\ncase", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order \"1002\" \\\ncase", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXIgXCIxMDAyXCIgXFxcbmNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.ae0ygxQzrDgNy0KujEN18MKMrR30K1-wwBJB3U8j5To", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXIgXCIxMDAyXCIgXFxcbmNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.ae0ygxQzrDgNy0KujEN18MKMrR30K1-wwBJB3U8j5To" + } + }, + { + "name": "a lone surrogate in the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-\ud800-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "correlation_id must be text without a lone surrogate" + }, + { + "name": "a lone low surrogate at the end of the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-\udfdf", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "correlation_id must be text without a lone surrogate" + }, + { + "name": "a surrogate pair the wrong way round in the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "\udfdf\ud835", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "correlation_id must be text without a lone surrogate" + }, + { + "name": "a lone surrogate in the graph id", + "message": { + "kind": "approval", + "graph_id": "order-\ud800", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "graph_id must be text without a lone surrogate" + }, + { + "name": "a lone surrogate in an advice's correlation id", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-\ud800-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "correlation_id must be text without a lone surrogate" + }, + { + "name": "a lone surrogate in an advice's graph id", + "message": { + "kind": "advice", + "graph_id": "\udc00", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "graph_id must be text without a lone surrogate" + }, + { + "name": "a lone surrogate in the graph id is told before a description that is missing", + "message": { + "kind": "approval", + "graph_id": "order-\ud800", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "graph_id must be text without a lone surrogate" + }, + { + "name": "a description that is missing is told before a lone surrogate in the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "correlation_id": "order-\ud800", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "description is required" + }, + { + "name": "a lone surrogate in the correlation id is told before a summary that is missing", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-\ud800", + "turn": 2, + "node": "assist", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "correlation_id must be text without a lone surrogate" + }, + { + "name": "requested_at at an offset is kept as written, and the expiry is in UTC", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:12:04.118+01:00" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T10:12:04.118+01:00", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "requested_at behind UTC, across midnight", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-18T23:42:04.118-09:30" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-18T23:42:04.118-09:30", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "requested_at to the minute", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.kCkyDIlwoirUDB6f29h1q4pluL_H_ioODtEtNJLpyVU", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.kCkyDIlwoirUDB6f29h1q4pluL_H_ioODtEtNJLpyVU" + } + }, + { + "name": "requested_at to the minute at an offset", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:12+01:00" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T10:12+01:00", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.kCkyDIlwoirUDB6f29h1q4pluL_H_ioODtEtNJLpyVU", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.kCkyDIlwoirUDB6f29h1q4pluL_H_ioODtEtNJLpyVU" + } + }, + { + "name": "requested_at with a fraction of one digit", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.1Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.1Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.100Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "requested_at with a fraction of nine digits: the expiry to the millisecond, cut", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118999999Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118999999Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "requested_at on the 29th of February of a leap year", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1s", + "requested_at": "2024-02-29T23:59:59Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2024-02-29T23:59:59Z", + "turn": 2, + "ttl": "1s", + "expires_at": "2024-03-01T00:00:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTcwOTI1MTIwMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.6MbkxT4XOaqTJcb3A2-LiuvU6WSBCaZE41nNydnozGk", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTcwOTI1MTIwMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.6MbkxT4XOaqTJcb3A2-LiuvU6WSBCaZE41nNydnozGk" + } + }, + { + "name": "requested_at in the year 0001", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1h", + "requested_at": "0001-01-01T00:00:00Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "0001-01-01T00:00:00Z", + "turn": 2, + "ttl": "1h", + "expires_at": "0001-01-01T01:00:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTYyMTM1NTkzMjAwLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.DbM_d16cBAoEICw6gK5rwtdOZGZA2q5wM1tOe9WyAM0", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTYyMTM1NTkzMjAwLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.DbM_d16cBAoEICw6gK5rwtdOZGZA2q5wM1tOe9WyAM0" + } + }, + { + "name": "requested_at in a year before 1000: the expiry's year in four digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "500ms", + "requested_at": "0999-12-31T23:59:59.5Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "0999-12-31T23:59:59.5Z", + "turn": 2, + "ttl": "500ms", + "expires_at": "1000-01-01T00:00:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTMwNjEwMjI0MDAwLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Ci136R-H-WUPsfln4i6s_nyib3xVFjA2S-P32CS-_hw", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTMwNjEwMjI0MDAwLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Ci136R-H-WUPsfln4i6s_nyib3xVFjA2S-P32CS-_hw" + } + }, + { + "name": "an expiry before 1970 with a fraction: its whole seconds are the floor", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1, + "requested_at": "1969-12-31T23:59:58.250Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "1969-12-31T23:59:58.250Z", + "turn": 2, + "ttl": 1, + "expires_at": "1969-12-31T23:59:59.250Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.wBOW5_f_KTnMKg_TLXgDjegSEr4ZRVy2A7xF6O8sxSM", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.wBOW5_f_KTnMKg_TLXgDjegSEr4ZRVy2A7xF6O8sxSM" + } + }, + { + "name": "an expiry a millisecond before 1970", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1s", + "requested_at": "1969-12-31T23:59:58.999Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "1969-12-31T23:59:58.999Z", + "turn": 2, + "ttl": "1s", + "expires_at": "1969-12-31T23:59:59.999Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.wBOW5_f_KTnMKg_TLXgDjegSEr4ZRVy2A7xF6O8sxSM", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.wBOW5_f_KTnMKg_TLXgDjegSEr4ZRVy2A7xF6O8sxSM" + } + }, + { + "name": "an expiry at the first instant of 1970", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1, + "requested_at": "1969-12-31T23:59:59Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "1969-12-31T23:59:59Z", + "turn": 2, + "ttl": 1, + "expires_at": "1970-01-01T00:00:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.3unpQxjq7ynmWN4PYP1hm3Ov2SyvmaAL0Rp88sFR6xQ", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.3unpQxjq7ynmWN4PYP1hm3Ov2SyvmaAL0Rp88sFR6xQ" + } + }, + { + "name": "an expiry after 1970 with a fraction", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1, + "requested_at": "1970-01-01T00:00:00.500Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "1970-01-01T00:00:00.500Z", + "turn": 2, + "ttl": 1, + "expires_at": "1970-01-01T00:00:01.500Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.NJOXt8qoAJxLMSK2AAbi9hNJbz_qajxreewRv0RmdFc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.NJOXt8qoAJxLMSK2AAbi9hNJbz_qajxreewRv0RmdFc" + } + }, + { + "name": "the last instant a wait can expire at", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1, + "requested_at": "9999-12-31T23:59:58.999Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "9999-12-31T23:59:58.999Z", + "turn": 2, + "ttl": 1, + "expires_at": "9999-12-31T23:59:59.999Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng" + } + }, + { + "name": "the longest wait from 1970, to the last second of the year 9999", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 253402300799, + "requested_at": "1970-01-01T00:00:00Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "1970-01-01T00:00:00Z", + "turn": 2, + "ttl": 253402300799, + "expires_at": "9999-12-31T23:59:59.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng" + } + }, + { + "name": "the longest wait from the first instant, in milliseconds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "315537897599999ms", + "requested_at": "0001-01-01T00:00:00Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "0001-01-01T00:00:00Z", + "turn": 2, + "ttl": "315537897599999ms", + "expires_at": "9999-12-31T23:59:59.999Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng" + } + }, + { + "name": "an advice's requested_at at an offset is kept as written", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T10:40:12.004+01:00" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T10:40:12.004+01:00", + "turn": 3 + } + }, + { + "name": "requested_at without an offset", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at a date alone", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a lower-case t", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19t09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a lower-case z", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a space for the T", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19 09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a space before", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": " 2026-11-19T09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a newline after", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04Z\n" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a byte order mark before", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at in the basic format", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "20261119T091204Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at a week date", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-W47-4" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at to the hour", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at on the 30th of February", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-02-30T09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at on the 29th of February of a common year", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-02-29T09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at at hour 24", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T24:00:00Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at at second 60", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-12-31T23:59:60Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a comma for the point", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04,118Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a fraction of ten digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.1180000001Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at at an offset of 24 hours", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04+24:00" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at at an offset without its colon", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04+0100" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at at an offset in hours alone", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04+01" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at in Arabic-Indic digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "٢٠٢٦-11-19T09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at in the year 0000", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "0000-06-01T00:00:00Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at in the year 0000 at an offset that puts the instant in the year 0001", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "0000-12-31T23:30:00-01:00" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at an offset puts before the year 0001", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "0001-01-01T00:00:00+00:01" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at an offset puts past the year 9999", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "9999-12-31T23:59:59-00:01" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at of empty text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at the seconds from 1970", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "1795079524" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "an advice's requested_at without an offset", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a summary that is missing is told before a requested_at that is no time", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04" + }, + "status": 400, + "error": "summary is required" + }, + { + "name": "a requested_at that is no time is told before a turn that is missing", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a wait that ends in the year 10000", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2913000d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a wait that ends at the first instant of the year 10000", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1, + "requested_at": "9999-12-31T23:59:59Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a wait that ends a millisecond past the last instant", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1ms", + "requested_at": "9999-12-31T23:59:59.999Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a wait from 1970 to the first second of the year 10000", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 253402300800, + "requested_at": "1970-01-01T00:00:00Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a wait of the most milliseconds a duration holds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "9007199254740991ms", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a wait of the most seconds a duration holds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 9007199254740, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a ttl that is no duration is told before a wait that ends too late", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "0", + "requested_at": "9999-12-31T23:59:59Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "calls that are missing are told before a wait that ends too late", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "ttl": "2913000d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "calls must be a non-empty list of the waiting calls, each with an id" + }, + { + "name": "graph_id of a no-break space", + "message": { + "kind": "approval", + "graph_id": " ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "graph_id is required" + }, + { + "name": "description of an ideographic space", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": " ", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "description is required" + }, + { + "name": "correlation_id of the line and the paragraph separator", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "

", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "correlation_id is required" + }, + { + "name": "summary of a tab, a newline and a space", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "\t\n ", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "summary is required" + }, + { + "name": "graph_id of every white-space character", + "message": { + "kind": "approval", + "graph_id": "\t\n\u000b\f\r              

   ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "graph_id is required" + }, + { + "name": "an advice's summary of a figure space", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": " ", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "summary is required" + }, + { + "name": "graph_id of a byte order mark, a character of a name", + "message": { + "kind": "approval", + "graph_id": "", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Iu-7vyIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.VYtphZGvM2eH_Dz7-t-Pi3x-G9vCcABuPrBcZM4plwY", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Iu-7vyIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.VYtphZGvM2eH_Dz7-t-Pi3x-G9vCcABuPrBcZM4plwY" + } + }, + { + "name": "correlation_id of a next-line character, a character of a name", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "…", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "…", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoiwoUiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.cXRicYp4O_kbACXcBVhkcD12XB796Z8zZPSRB3SdHUc", + "link": "https://ask.example.test/ask/v1.eyJjIjoiwoUiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.cXRicYp4O_kbACXcBVhkcD12XB796Z8zZPSRB3SdHUc" + } + }, + { + "name": "description of a file separator, a character of a name", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "\u001c", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "\u001c", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "summary of a unit separator, a character of a name", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "\u001f", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "\u001f", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "graph_id of a zero-width space, a character of a name", + "message": { + "kind": "approval", + "graph_id": "​", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "​", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IuKAiyIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.OrhPNe78l87hFwb2Qx8paxqPkFABVbx6KrwFp8fyUZw", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IuKAiyIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.OrhPNe78l87hFwb2Qx8paxqPkFABVbx6KrwFp8fyUZw" + } + }, + { + "name": "an advice's summary of a group and a record separator", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "\u001d\u001e", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "acknowledge", + "summary": "\u001d\u001e", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z", + "turn": 3 + } + }, + { + "name": "graph_id with white space around a name is kept as written", + "message": { + "kind": "approval", + "graph_id": " order-assistant ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": " order-assistant ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IiBvcmRlci1hc3Npc3RhbnTCoCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.cw64YnmxZtgEyt40KmzoeS9DuCpqQP9C_fdjE-c7aAc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IiBvcmRlci1hc3Npc3RhbnTCoCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.cw64YnmxZtgEyt40KmzoeS9DuCpqQP9C_fdjE-c7aAc" + } + }, + { + "name": "the largest turn, in ASCII digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2147483647", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2147483647, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc" + } + }, + { + "name": "the largest turn, as a float", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483647.0, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2147483647, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc" + } + }, + { + "name": "an advice's turn, the largest", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483647, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z", + "turn": 2147483647 + } + }, + { + "name": "a turn one past the largest, in ASCII digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2147483648", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn one past the largest, as a float", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483648.0, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of 4294967296", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 4294967296, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of the largest whole number", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 9007199254740991, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn one past the largest whole number", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 9007199254740992, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "an advice's turn one past the largest", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483648, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + } + ], + "readvice_cases": [ + { + "name": "the re-advice of an approval", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/order-assistant", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2 + } + } + }, + { + "name": "a graph that is not in the allowlist", + "payload": { + "g": "other-graph", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph other-graph is not configured for replies" + }, + { + "name": "a graph named constructor is not in the allowlist", + "payload": { + "g": "constructor", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph constructor is not configured for replies" + }, + { + "name": "a graph named toString is not in the allowlist", + "payload": { + "g": "toString", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph toString is not configured for replies" + }, + { + "name": "a graph named valueOf is not in the allowlist", + "payload": { + "g": "valueOf", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph valueOf is not configured for replies" + }, + { + "name": "a graph named hasOwnProperty is not in the allowlist", + "payload": { + "g": "hasOwnProperty", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph hasOwnProperty is not configured for replies" + }, + { + "name": "a graph named __proto__ is not in the allowlist", + "payload": { + "g": "__proto__", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph __proto__ is not configured for replies" + }, + { + "name": "a graph named prototype is not in the allowlist", + "payload": { + "g": "prototype", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph prototype is not configured for replies" + }, + { + "name": "a graph the allowlist names __proto__", + "payload": { + "g": "__proto__", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant", + "__proto__": "http://127.0.0.1:8085/api/graph/proto" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/proto", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2 + } + } + }, + { + "name": "a graph the allowlist names constructor", + "payload": { + "g": "constructor", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant", + "constructor": "http://127.0.0.1:8085/api/graph/constructor" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/constructor", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2 + } + } + } + ], + "reply_cases": [ + { + "name": "an approval with a note", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed the loss" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/order-assistant", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "[operator-17 at 2026-11-19T10:00:00.000Z] Carrier confirmed the loss" + } + ] + } + } + }, + { + "name": "a refusal without a note", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": false + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/order-assistant", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2, + "decisions": [ + { + "id": "toolu_01A", + "approved": false, + "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" + } + ] + } + } + }, + { + "name": "a refusal with an empty note", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": false, + "note": "" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/order-assistant", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2, + "decisions": [ + { + "id": "toolu_01A", + "approved": false, + "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" + } + ] + } + } + }, + { + "name": "a question's answer travels unchanged", + "payload": { + "g": "plan-assistant", + "c": "release-42", + "t": 4, + "k": "question", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_02B", + "answer": "B" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/plan-assistant", + "headers": { + "x-correlation-id": "release-42" + }, + "body": { + "turn": 4, + "decisions": [ + { + "id": "toolu_02B", + "answer": "B" + } + ] + } + } + }, + { + "name": "a question's answer may be any JSON value", + "payload": { + "g": "plan-assistant", + "c": "release-42", + "t": 4, + "k": "question", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_02B", + "answer": { + "plan": "B", + "why": "cheaper" + } + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/plan-assistant", + "headers": { + "x-correlation-id": "release-42" + }, + "body": { + "turn": 4, + "decisions": [ + { + "id": "toolu_02B", + "answer": { + "plan": "B", + "why": "cheaper" + } + } + ] + } + } + }, + { + "name": "a turn with a tool call and a question", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true + }, + { + "id": "toolu_02B", + "answer": "A" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/order-assistant", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" + }, + { + "id": "toolu_02B", + "answer": "A" + } + ] + } + } + }, + { + "name": "decisions empty", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "decisions must be a non-empty list, one per waiting call" + }, + { + "name": "decisions not a list", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": { + "id": "toolu_01A", + "approved": true + }, + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "decisions must be a non-empty list, one per waiting call" + }, + { + "name": "a decision without an id", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "approved": true + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "each decision needs the id of its call" + }, + { + "name": "a decision with approved and answer", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "answer": "x" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "each decision carries approved (with an optional note) or answer, not both" + }, + { + "name": "a decision with neither", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "note": "x" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "each decision carries approved (with an optional note) or answer" + }, + { + "name": "approved not a boolean", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": "yes" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "approved must be true or false" + }, + { + "name": "note not text", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": 5 + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "note must be text" + }, + { + "name": "an answer with a note", + "payload": { + "g": "plan-assistant", + "c": "release-42", + "t": 4, + "k": "question", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_02B", + "answer": "B", + "note": "x" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "a question's decision carries an answer and no note" + }, + { + "name": "a graph that is not in the allowlist", + "payload": { + "g": "other-graph", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph other-graph is not configured for replies" + }, + { + "name": "a decision for a graph named constructor, which is not in the allowlist", + "payload": { + "g": "constructor", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed the loss" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "status": 404, + "error": "graph constructor is not configured for replies" + }, + { + "name": "a decision for a graph named __proto__, which is not in the allowlist", + "payload": { + "g": "__proto__", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed the loss" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "status": 404, + "error": "graph __proto__ is not configured for replies" + } + ], + "outcome_cases": [ + { + "name": "the graph answered", + "engine": { + "status": 200, + "body": "{\"type\": \"answer\", \"turn\": 3, \"run\": \"resume\", \"message\": \"Your refund has been issued.\"}", + "error": null + }, + "status": 200, + "body": { + "type": "answer", + "turn": 3, + "run": "resume", + "message": "Your refund has been issued." + } + }, + { + "name": "the model asked again", + "engine": { + "status": 200, + "body": "{\"type\": \"approval\", \"turn\": 4, \"calls\": []}", + "error": null + }, + "status": 200, + "body": { + "type": "approval", + "turn": 4, + "calls": [] + } + }, + { + "name": "nothing waiting (the gate)", + "engine": { + "status": 410, + "body": "{\"type\": \"nothing-waiting\"}", + "error": null + }, + "status": 410, + "body": { + "type": "nothing-waiting" + } + }, + { + "name": "the graph refused the decisions", + "engine": { + "status": 400, + "body": "{\"type\": \"error\", \"message\": \"unknown call id\"}", + "error": null + }, + "status": 400, + "body": { + "type": "error", + "message": "unknown call id" + } + }, + { + "name": "the graph failed", + "engine": { + "status": 500, + "body": "{\"type\": \"error\", \"message\": \"boom\"}", + "error": null + }, + "status": 500, + "body": { + "type": "error", + "message": "boom" + } + }, + { + "name": "the graph answered text", + "engine": { + "status": 200, + "body": "OK", + "error": null + }, + "status": 502, + "body": { + "type": "error", + "message": "the graph answered outside the contract" + } + }, + { + "name": "the graph answered a JSON list", + "engine": { + "status": 200, + "body": "[1,2]", + "error": null + }, + "status": 502, + "body": { + "type": "error", + "message": "the graph answered outside the contract" + } + }, + { + "name": "the graph answered nothing", + "engine": { + "status": 200, + "body": "", + "error": null + }, + "status": 502, + "body": { + "type": "error", + "message": "the graph answered outside the contract" + } + }, + { + "name": "the graph did not answer", + "engine": { + "status": null, + "body": null, + "error": "ClientConnectorError" + }, + "status": 502, + "body": { + "type": "error", + "message": "the graph did not answer - ClientConnectorError" + } + }, + { + "name": "the graph timed out", + "engine": { + "status": null, + "body": null, + "error": "TimeoutError" + }, + "status": 502, + "body": { + "type": "error", + "message": "the graph did not answer - TimeoutError" + } + } + ], + "record_cases": [ + { + "name": "an approval", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "now": "2026-11-19T09:12:05.000Z", + "key": [ + "order-assistant", + "order-1002-case", + 2 + ], + "row": { + "kind": "approval", + "graph_id": "order-assistant", + "correlation_id": "order-1002-case", + "turn": 2, + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac", + "description": "Customer-support assistant: a refund waits for a supervisor", + "summary": "A refund waits for the supervisor's decision", + "details": null, + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "state": "open", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "updated_at": "2026-11-19T09:12:05.000Z", + "answered_at": null, + "answered_by": null, + "decisions": null, + "outcome": null + } + }, + { + "name": "a question", + "event": { + "kind": "question", + "graph_id": "plan-assistant", + "description": "Planning assistant: the owner picks one of the plans", + "correlation_id": "release-42", + "turn": 1, + "node": "plan", + "summary": "The planning assistant asks which plan to follow", + "calls": [ + { + "id": "toolu_02B", + "name": "ask_owner", + "ask": true, + "wait": true, + "input": { + "question": "Which plan?", + "options": [ + "A", + "B", + "C" + ] + } + } + ], + "ttl": 3600, + "requested_at": "2026-11-19T09:20:00.000Z", + "expires_at": "2026-11-19T10:20:00.000Z", + "ticket": "v1.plan.mac", + "link": "https://ask.example.test/ask/v1.plan.mac" + }, + "now": "2026-11-19T09:12:05.000Z", + "key": [ + "plan-assistant", + "release-42", + 1 + ], + "row": { + "kind": "question", + "graph_id": "plan-assistant", + "correlation_id": "release-42", + "turn": 1, + "ticket": "v1.plan.mac", + "link": "https://ask.example.test/ask/v1.plan.mac", + "description": "Planning assistant: the owner picks one of the plans", + "summary": "The planning assistant asks which plan to follow", + "details": null, + "message": { + "kind": "question", + "graph_id": "plan-assistant", + "description": "Planning assistant: the owner picks one of the plans", + "correlation_id": "release-42", + "turn": 1, + "node": "plan", + "summary": "The planning assistant asks which plan to follow", + "calls": [ + { + "id": "toolu_02B", + "name": "ask_owner", + "ask": true, + "wait": true, + "input": { + "question": "Which plan?", + "options": [ + "A", + "B", + "C" + ] + } + } + ], + "ttl": 3600, + "requested_at": "2026-11-19T09:20:00.000Z", + "expires_at": "2026-11-19T10:20:00.000Z", + "ticket": "v1.plan.mac", + "link": "https://ask.example.test/ask/v1.plan.mac" + }, + "state": "open", + "requested_at": "2026-11-19T09:20:00.000Z", + "expires_at": "2026-11-19T10:20:00.000Z", + "updated_at": "2026-11-19T09:12:05.000Z", + "answered_at": null, + "answered_by": null, + "decisions": null, + "outcome": null + } + }, + { + "name": "an advice with a turn", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "now": "2026-11-19T09:12:05.000Z", + "key": null, + "row": { + "kind": "advice", + "graph_id": "order-assistant", + "correlation_id": "order-1002-case", + "turn": 2, + "ticket": null, + "link": null, + "description": "Customer-support assistant: a refund waits for a supervisor", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "state": null, + "requested_at": "2026-11-19T09:40:12.004Z", + "expires_at": null, + "updated_at": "2026-11-19T09:12:05.000Z", + "answered_at": null, + "answered_by": null, + "decisions": null, + "outcome": null + } + }, + { + "name": "an advice without a turn or a requested_at takes now", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant", + "correlation_id": "order-1002-case", + "summary": "Nightly: the queue is empty" + }, + "now": "2026-11-19T09:12:05.000Z", + "key": null, + "row": { + "kind": "advice", + "graph_id": "order-assistant", + "correlation_id": "order-1002-case", + "turn": null, + "ticket": null, + "link": null, + "description": "Customer-support assistant", + "summary": "Nightly: the queue is empty", + "details": null, + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant", + "correlation_id": "order-1002-case", + "summary": "Nightly: the queue is empty" + }, + "state": null, + "requested_at": "2026-11-19T09:12:05.000Z", + "expires_at": null, + "updated_at": "2026-11-19T09:12:05.000Z", + "answered_at": null, + "answered_by": null, + "decisions": null, + "outcome": null + } + } + ], + "answer_cases": [ + { + "name": "the engine answered", + "status": 200, + "body": { + "type": "answer", + "turn": 3, + "message": "Your refund has been issued." + }, + "state": "answered" + }, + { + "name": "the model asked again", + "status": 200, + "body": { + "type": "approval", + "turn": 4, + "calls": [] + }, + "state": "answered" + }, + { + "name": "the loop refused the decision - the graph re-advised with the error", + "status": 200, + "body": { + "type": "approval", + "turn": 2, + "error": "not a call waiting for approval" + }, + "state": "open" + }, + { + "name": "nothing waiting by status", + "status": 410, + "body": { + "type": "nothing-waiting" + }, + "state": "expired" + }, + { + "name": "nothing waiting by type", + "status": 200, + "body": { + "type": "nothing-waiting" + }, + "state": "expired" + }, + { + "name": "the ticket expired at the reply endpoint", + "status": 410, + "body": { + "type": "expired", + "message": "Ticket expired" + }, + "state": "expired" + }, + { + "name": "the reply endpoint refused the decisions", + "status": 400, + "body": { + "type": "error", + "message": "each decision needs the id of its call" + }, + "state": "open" + }, + { + "name": "the graph did not answer", + "status": 502, + "body": { + "type": "error", + "message": "the graph did not answer - TimeoutError" + }, + "state": "open" + }, + { + "name": "the reply endpoint did not answer", + "status": 502, + "body": { + "type": "error", + "message": "the reply endpoint did not answer - ClientConnectorError" + }, + "state": "open" + }, + { + "name": "an answer with no body", + "status": 200, + "body": null, + "state": "answered" + } + ], + "transition_cases": [ + { + "name": "the reference sequence", + "steps": [ + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "now": "2026-11-19T09:12:05.000Z" + }, + { + "op": "record", + "event": { + "kind": "question", + "graph_id": "plan-assistant", + "description": "Planning assistant: the owner picks one of the plans", + "correlation_id": "release-42", + "turn": 1, + "node": "plan", + "summary": "The planning assistant asks which plan to follow", + "calls": [ + { + "id": "toolu_02B", + "name": "ask_owner", + "ask": true, + "wait": true, + "input": { + "question": "Which plan?", + "options": [ + "A", + "B", + "C" + ] + } + } + ], + "ttl": 3600, + "requested_at": "2026-11-19T09:20:00.000Z", + "expires_at": "2026-11-19T10:20:00.000Z", + "ticket": "v1.plan.mac", + "link": "https://ask.example.test/ask/v1.plan.mac" + }, + "now": "2026-11-19T09:20:01.000Z" + }, + { + "op": "record", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant", + "correlation_id": "order-1002-case", + "summary": "Nightly: the queue is empty" + }, + "now": "2026-11-19T09:30:00.000Z" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:35:00.000Z", + "expires_at": "2026-11-21T09:35:00.000Z", + "ticket": "v1.payload2.mac", + "link": "https://ask.example.test/ask/v1.payload2.mac" + }, + "now": "2026-11-19T09:35:00.500Z", + "note": "a re-advice for the same turn updates the same row with the new ticket" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-1002-case", + 2 + ], + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed" + } + ], + "who": "operator-17", + "status": 200, + "body": { + "type": "answer", + "turn": 3 + }, + "now": "2026-11-19T09:40:00.000Z" + }, + { + "op": "record", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "now": "2026-11-19T09:40:12.100Z" + }, + { + "op": "expire", + "now": "2026-11-19T10:30:00.000Z", + "note": "the question's hour is over; the answered wait is untouched" + }, + { + "op": "since", + "seq": 4, + "limit": 10 + }, + { + "op": "since", + "seq": 0, + "limit": 3 + } + ], + "results": [ + { + "id": 1, + "seq": 1, + "state": "open", + "ticket": "v1.payload.mac" + }, + { + "id": 2, + "seq": 2, + "state": "open", + "ticket": "v1.plan.mac" + }, + { + "id": 3, + "seq": 3, + "state": null, + "ticket": null + }, + { + "id": 1, + "seq": 4, + "state": "open", + "ticket": "v1.payload2.mac" + }, + { + "id": 1, + "seq": 5, + "state": "answered", + "answered_by": "operator-17" + }, + { + "id": 4, + "seq": 6, + "state": null, + "ticket": null + }, + { + "expired": [ + { + "id": 2, + "seq": 7 + } + ] + }, + { + "ids": [ + 1, + 4, + 2 + ], + "seqs": [ + 5, + 6, + 7 + ] + }, + { + "ids": [ + 3, + 1, + 4 + ], + "seqs": [ + 3, + 5, + 6 + ] + } + ], + "final": [ + { + "id": 1, + "seq": 5, + "kind": "approval", + "state": "answered", + "ticket": "v1.payload2.mac", + "turn": 2, + "requested_at": "2026-11-19T09:35:00.000Z", + "expires_at": "2026-11-21T09:35:00.000Z", + "updated_at": "2026-11-19T09:40:00.000Z", + "answered_by": "operator-17", + "outcome": { + "status": 200, + "body": { + "type": "answer", + "turn": 3 + } + } + }, + { + "id": 2, + "seq": 7, + "kind": "question", + "state": "expired", + "ticket": "v1.plan.mac", + "turn": 1, + "requested_at": "2026-11-19T09:20:00.000Z", + "expires_at": "2026-11-19T10:20:00.000Z", + "updated_at": "2026-11-19T10:30:00.000Z", + "answered_by": null, + "outcome": null + }, + { + "id": 3, + "seq": 3, + "kind": "advice", + "state": null, + "ticket": null, + "turn": null, + "requested_at": "2026-11-19T09:30:00.000Z", + "expires_at": null, + "updated_at": "2026-11-19T09:30:00.000Z", + "answered_by": null, + "outcome": null + }, + { + "id": 4, + "seq": 6, + "kind": "advice", + "state": null, + "ticket": null, + "turn": 2, + "requested_at": "2026-11-19T09:40:12.004Z", + "expires_at": null, + "updated_at": "2026-11-19T09:40:12.100Z", + "answered_by": null, + "outcome": null + } + ] + }, + { + "name": "two devices on one card - the first accepted decision stands", + "steps": [ + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1004-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1004", + "amount": 240.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:00:00.000Z", + "expires_at": "2026-11-21T10:00:00.000Z", + "ticket": "v1.two.mac", + "link": "https://ask.example.test/ask/v1.two.mac" + }, + "now": "2026-11-19T10:00:00.200Z" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-1004-case", + 2 + ], + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "from device-2" + } + ], + "who": "device-2", + "status": 410, + "body": { + "type": "nothing-waiting", + "run": "fresh" + }, + "now": "2026-11-19T10:00:01.000Z", + "note": "two devices clicked at once; the engine took the other one's decision, so this one got nothing-waiting, and it lands first: the open row turns expired for a moment" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-1004-case", + 2 + ], + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "from device-1" + } + ], + "who": "device-1", + "status": 200, + "body": { + "type": "answer", + "turn": 3 + }, + "now": "2026-11-19T10:00:02.000Z", + "note": "the accepted decision always wins the row" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-1004-case", + 2 + ], + "decisions": [ + { + "id": "toolu_01A", + "approved": false + } + ], + "who": "device-3", + "status": 410, + "body": { + "type": "nothing-waiting", + "run": "fresh" + }, + "now": "2026-11-19T10:00:03.000Z", + "note": "a nothing-waiting after the acceptance changes nothing: the row stands as device-1 left it and the sequence does not move" + }, + { + "op": "since", + "seq": 0, + "limit": 10 + } + ], + "results": [ + { + "id": 1, + "seq": 1, + "state": "open", + "ticket": "v1.two.mac" + }, + { + "id": 1, + "seq": 2, + "state": "expired", + "answered_by": "device-2" + }, + { + "id": 1, + "seq": 3, + "state": "answered", + "answered_by": "device-1" + }, + { + "id": 1, + "seq": 3, + "state": "answered", + "answered_by": "device-1" + }, + { + "ids": [ + 1 + ], + "seqs": [ + 3 + ] + } + ], + "final": [ + { + "id": 1, + "seq": 3, + "kind": "approval", + "state": "answered", + "ticket": "v1.two.mac", + "turn": 2, + "requested_at": "2026-11-19T10:00:00.000Z", + "expires_at": "2026-11-21T10:00:00.000Z", + "updated_at": "2026-11-19T10:00:02.000Z", + "answered_by": "device-1", + "outcome": { + "status": 200, + "body": { + "type": "answer", + "turn": 3 + } + } + } + ] + }, + { + "name": "an older message landing late never overwrites a newer row, and an answer needs a recorded wait", + "steps": [ + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1007-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1007", + "amount": 60.0, + "reason": "Damaged on arrival" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T11:00:00.000Z", + "expires_at": "2026-11-21T11:00:00.000Z", + "ticket": "v1.first.mac", + "link": "https://ask.example.test/ask/v1.first.mac" + }, + "now": "2026-11-19T11:00:00.200Z" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1007-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1007", + "amount": 60.0, + "reason": "Damaged on arrival" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:59:00.000Z", + "expires_at": "2026-11-21T10:59:00.000Z", + "ticket": "v1.stale.mac", + "link": "https://ask.example.test/ask/v1.stale.mac" + }, + "now": "2026-11-19T11:00:00.300Z", + "note": "a message older than the row lands late (two recorder workers, or a redelivery): the row stands and the sequence does not move" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1007-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1007", + "amount": 60.0, + "reason": "Damaged on arrival" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T11:05:00.000Z", + "expires_at": "2026-11-21T11:05:00.000Z", + "ticket": "v1.newer.mac", + "link": "https://ask.example.test/ask/v1.newer.mac" + }, + "now": "2026-11-19T11:05:00.100Z", + "note": "a newer re-advice updates the row with its ticket" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-1007-case", + 2 + ], + "decisions": [ + { + "id": "toolu_01A", + "approved": true + } + ], + "who": "operator-17", + "status": 200, + "body": { + "type": "answer", + "turn": 3 + }, + "now": "2026-11-19T11:06:00.000Z" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-9999-case", + 7 + ], + "decisions": [ + { + "id": "toolu_09Z", + "approved": true + } + ], + "who": "operator-17", + "status": 200, + "body": { + "type": "answer", + "turn": 8 + }, + "now": "2026-11-19T11:06:30.000Z", + "note": "an answer for a wait that was never recorded: nothing to write, the result is null" + }, + { + "op": "since", + "seq": 0, + "limit": 10 + } + ], + "results": [ + { + "id": 1, + "seq": 1, + "state": "open", + "ticket": "v1.first.mac" + }, + { + "id": 1, + "seq": 1, + "state": "open", + "ticket": "v1.first.mac" + }, + { + "id": 1, + "seq": 2, + "state": "open", + "ticket": "v1.newer.mac" + }, + { + "id": 1, + "seq": 3, + "state": "answered", + "answered_by": "operator-17" + }, + null, + { + "ids": [ + 1 + ], + "seqs": [ + 3 + ] + } + ], + "final": [ + { + "id": 1, + "seq": 3, + "kind": "approval", + "state": "answered", + "ticket": "v1.newer.mac", + "turn": 2, + "requested_at": "2026-11-19T11:05:00.000Z", + "expires_at": "2026-11-21T11:05:00.000Z", + "updated_at": "2026-11-19T11:06:00.000Z", + "answered_by": "operator-17", + "outcome": { + "status": 200, + "body": { + "type": "answer", + "turn": 3 + } + } + } + ] + }, + { + "name": "times in another spelling are ordered by their instants, never by their texts", + "steps": [ + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:12:04.118+01:00", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.first.mac", + "link": "https://ask.example.test/ask/v1.first.mac" + }, + "now": "2026-11-19T09:12:05.000Z" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:30:00Z", + "expires_at": "2026-11-21T09:30:00.000Z", + "ticket": "v1.second.mac", + "link": "https://ask.example.test/ask/v1.second.mac" + }, + "now": "2026-11-19T09:30:01.000Z", + "note": "a later instant whose text sorts before the row's: the row is updated" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:00:00+02:00", + "expires_at": "2026-11-21T08:00:00.000Z", + "ticket": "v1.late.mac", + "link": "https://ask.example.test/ask/v1.late.mac" + }, + "now": "2026-11-19T09:31:00.000Z", + "note": "an earlier instant whose text sorts after the row's: the row is kept" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:30:00.000+00:00", + "expires_at": "2026-11-21T09:30:00.000Z", + "ticket": "v1.same.mac", + "link": "https://ask.example.test/ask/v1.same.mac" + }, + "now": "2026-11-19T09:32:00.000Z", + "note": "the same instant in another spelling is not older: the row is updated" + }, + { + "op": "expire", + "now": "2026-11-21T10:30:00+01:00", + "note": "the instant of the expiry itself, written at an offset: not past it" + }, + { + "op": "expire", + "now": "2026-11-21T09:30:00.001Z", + "note": "a millisecond past the expiry" + }, + { + "op": "since", + "seq": 0, + "limit": 10 + } + ], + "results": [ + { + "id": 1, + "seq": 1, + "state": "open", + "ticket": "v1.first.mac" + }, + { + "id": 1, + "seq": 2, + "state": "open", + "ticket": "v1.second.mac" + }, + { + "id": 1, + "seq": 2, + "state": "open", + "ticket": "v1.second.mac" + }, + { + "id": 1, + "seq": 3, + "state": "open", + "ticket": "v1.same.mac" + }, + { + "expired": [] + }, + { + "expired": [ + { + "id": 1, + "seq": 4 + } + ] + }, + { + "ids": [ + 1 + ], + "seqs": [ + 4 + ] + } + ], + "final": [ + { + "id": 1, + "seq": 4, + "kind": "approval", + "state": "expired", + "ticket": "v1.same.mac", + "turn": 2, + "requested_at": "2026-11-19T09:30:00.000+00:00", + "expires_at": "2026-11-21T09:30:00.000Z", + "updated_at": "2026-11-21T09:30:00.001Z", + "answered_by": null, + "outcome": null + } + ] + } + ], + "number_cases": [ + { + "name": "ASCII digits", + "value": "512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a single digit", + "value": "1", + "whole": 1, + "duration_ms": 1000 + }, + { + "name": "zero as text", + "value": "0", + "whole": 0, + "duration_ms": 0 + }, + { + "name": "leading zeros", + "value": "007", + "whole": 7, + "duration_ms": 7000 + }, + { + "name": "forty leading zeros", + "value": "00000000000000000000000000000000000000001", + "whole": 1, + "duration_ms": 1000 + }, + { + "name": "spaces around", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a tab and a newline around", + "value": "\t512\n", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "no-break spaces around", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "an ideographic space before", + "value": " 512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a line separator before", + "value": "
512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a space inside", + "value": "5 12", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark before", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark after", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a next-line character after", + "value": "512…", + "whole": null, + "duration_ms": null + }, + { + "name": "a file separator before", + "value": "\u001c512", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit separator after", + "value": "512\u001f", + "whole": null, + "duration_ms": null + }, + { + "name": "a zero-width space before", + "value": "​512", + "whole": null, + "duration_ms": null + }, + { + "name": "empty text", + "value": "", + "whole": null, + "duration_ms": null + }, + { + "name": "blank text", + "value": " ", + "whole": null, + "duration_ms": null + }, + { + "name": "a plus sign", + "value": "+5", + "whole": null, + "duration_ms": null + }, + { + "name": "a minus sign", + "value": "-5", + "whole": null, + "duration_ms": null + }, + { + "name": "an underscore", + "value": "5_0", + "whole": null, + "duration_ms": null + }, + { + "name": "a point in text", + "value": "5.0", + "whole": null, + "duration_ms": null + }, + { + "name": "an exponent in text", + "value": "5e2", + "whole": null, + "duration_ms": null + }, + { + "name": "hexadecimal text", + "value": "0x10", + "whole": null, + "duration_ms": null + }, + { + "name": "a word", + "value": "five", + "whole": null, + "duration_ms": null + }, + { + "name": "an Arabic-Indic digit", + "value": "٣", + "whole": null, + "duration_ms": null + }, + { + "name": "Arabic-Indic digits", + "value": "٥١٢", + "whole": null, + "duration_ms": null + }, + { + "name": "ASCII then Arabic-Indic", + "value": "5٣", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth digits", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a Devanagari digit", + "value": "५", + "whole": null, + "duration_ms": null + }, + { + "name": "a mathematical bold digit", + "value": "𝟓", + "whole": null, + "duration_ms": null + }, + { + "name": "superscript two", + "value": "²", + "whole": null, + "duration_ms": null + }, + { + "name": "ASCII then superscript", + "value": "5²", + "whole": null, + "duration_ms": null + }, + { + "name": "subscript two", + "value": "₂", + "whole": null, + "duration_ms": null + }, + { + "name": "a circled digit", + "value": "①", + "whole": null, + "duration_ms": null + }, + { + "name": "a vulgar fraction", + "value": "½", + "whole": null, + "duration_ms": null + }, + { + "name": "a Roman numeral", + "value": "Ⅷ", + "whole": null, + "duration_ms": null + }, + { + "name": "an ideographic number", + "value": "五", + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number as text", + "value": "9007199254740991", + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "one above the largest as text", + "value": "9007199254740992", + "whole": null, + "duration_ms": null + }, + { + "name": "twenty nines", + "value": "99999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "four hundred nines", + "value": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "five thousand nines", + "value": "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "a number", + "value": 512, + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "zero", + "value": 0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "a negative number", + "value": -5, + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number", + "value": 9007199254740991, + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "one above the largest", + "value": 9007199254740992, + "whole": null, + "duration_ms": null + }, + { + "name": "a number of twenty nines", + "value": 99999999999999999999, + "whole": null, + "duration_ms": null + }, + { + "name": "a float with a whole value", + "value": 16000.0, + "whole": 16000, + "duration_ms": 16000000 + }, + { + "name": "float zero", + "value": 0.0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "negative zero", + "value": -0.0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "a negative float with a whole value", + "value": -1.0, + "whole": null, + "duration_ms": null + }, + { + "name": "a float with a fraction", + "value": 2.5, + "whole": null, + "duration_ms": null + }, + { + "name": "a float just above a whole value", + "value": 5.000000000000001, + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number as a float", + "value": 9007199254740991.0, + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "a float above the largest", + "value": 1e+16, + "whole": null, + "duration_ms": null + }, + { + "name": "a huge float", + "value": 1e+300, + "whole": null, + "duration_ms": null + }, + { + "name": "true", + "value": true, + "whole": null, + "duration_ms": null + }, + { + "name": "false", + "value": false, + "whole": null, + "duration_ms": null + }, + { + "name": "null", + "value": null, + "whole": null, + "duration_ms": null + }, + { + "name": "a list", + "value": [ + 5 + ], + "whole": null, + "duration_ms": null + }, + { + "name": "a map", + "value": { + "value": 5 + }, + "whole": null, + "duration_ms": null + }, + { + "name": "minutes", + "value": "30m", + "whole": null, + "duration_ms": 1800000 + }, + { + "name": "hours", + "value": "12h", + "whole": null, + "duration_ms": 43200000 + }, + { + "name": "days", + "value": "2d", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "seconds", + "value": "45s", + "whole": null, + "duration_ms": 45000 + }, + { + "name": "zero days", + "value": "0d", + "whole": null, + "duration_ms": 0 + }, + { + "name": "spaces around a duration", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "a space before the unit", + "value": "2 d", + "whole": null, + "duration_ms": null + }, + { + "name": "an upper-case unit", + "value": "2D", + "whole": null, + "duration_ms": null + }, + { + "name": "an unknown unit", + "value": "2w", + "whole": null, + "duration_ms": null + }, + { + "name": "two units", + "value": "1d12h", + "whole": null, + "duration_ms": null + }, + { + "name": "a fraction of an hour", + "value": "1.5h", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit alone", + "value": "d", + "whole": null, + "duration_ms": null + }, + { + "name": "Arabic-Indic hours", + "value": "٣h", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth hours", + "value": "12h", + "whole": null, + "duration_ms": null + }, + { + "name": "a fullwidth unit", + "value": "2d", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark before a duration", + "value": "2d", + "whole": null, + "duration_ms": null + }, + { + "name": "a next-line character after a duration", + "value": "2d…", + "whole": null, + "duration_ms": null + }, + { + "name": "days past the most milliseconds", + "value": "104249991374d", + "whole": null, + "duration_ms": null + }, + { + "name": "a day more past the most milliseconds", + "value": "104249991375d", + "whole": null, + "duration_ms": null + }, + { + "name": "twenty nines of days", + "value": "99999999999999999999d", + "whole": null, + "duration_ms": null + }, + { + "name": "a range of pages", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages and ranges", + "value": "1-3,7", + "whole": null, + "duration_ms": null + }, + { + "name": "pages in the order named", + "value": "7,1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with spaces", + "value": " 2 - 3 , 1 ", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with no-break spaces", + "value": "1 - 3", + "whole": null, + "duration_ms": null + }, + { + "name": "two pages without a comma", + "value": "1 3", + "whole": null, + "duration_ms": null + }, + { + "name": "a space inside a page of a range", + "value": "1 0-12", + "whole": null, + "duration_ms": null + }, + { + "name": "line breaks around a hyphen", + "value": "1\n-\n3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with a byte order mark", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with a next-line character", + "value": "1…-3", + "whole": null, + "duration_ms": null + }, + { + "name": "an Arabic-Indic page", + "value": "1-٣", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth pages", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "a fullwidth hyphen", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "an en dash", + "value": "1–3", + "whole": null, + "duration_ms": null + }, + { + "name": "a range from page zero", + "value": "0-3", + "whole": null, + "duration_ms": null + }, + { + "name": "a range to the largest page", + "value": "1-9007199254740991", + "whole": null, + "duration_ms": null + }, + { + "name": "a range beyond the largest page", + "value": "1-9007199254740992", + "whole": null, + "duration_ms": null + }, + { + "name": "milliseconds", + "value": "500ms", + "whole": null, + "duration_ms": 500 + }, + { + "name": "zero milliseconds", + "value": "0ms", + "whole": null, + "duration_ms": 0 + }, + { + "name": "leading zeros and a unit", + "value": "007m", + "whole": null, + "duration_ms": 420000 + }, + { + "name": "spaces around milliseconds", + "value": " 250ms ", + "whole": null, + "duration_ms": 250 + }, + { + "name": "a space before ms", + "value": "500 ms", + "whole": null, + "duration_ms": null + }, + { + "name": "an upper-case ms", + "value": "500MS", + "whole": null, + "duration_ms": null + }, + { + "name": "ms alone", + "value": "ms", + "whole": null, + "duration_ms": null + }, + { + "name": "ms then s", + "value": "5mss", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit before the number", + "value": "s5", + "whole": null, + "duration_ms": null + }, + { + "name": "a minus sign and a unit", + "value": "-5s", + "whole": null, + "duration_ms": null + }, + { + "name": "a float and a unit", + "value": "5.0s", + "whole": null, + "duration_ms": null + }, + { + "name": "the most milliseconds", + "value": "9007199254740991ms", + "whole": null, + "duration_ms": 9007199254740991 + }, + { + "name": "one millisecond more", + "value": "9007199254740992ms", + "whole": null, + "duration_ms": null + }, + { + "name": "the most seconds", + "value": "9007199254740s", + "whole": null, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more", + "value": "9007199254741s", + "whole": null, + "duration_ms": null + }, + { + "name": "the most seconds without a unit", + "value": "9007199254740", + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more without a unit", + "value": "9007199254741", + "whole": 9007199254741, + "duration_ms": null + }, + { + "name": "the most seconds as a number", + "value": 9007199254740, + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more as a number", + "value": 9007199254741, + "whole": 9007199254741, + "duration_ms": null + }, + { + "name": "the most seconds as a float", + "value": 9007199254740.0, + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "the most minutes", + "value": "150119987579m", + "whole": null, + "duration_ms": 9007199254740000 + }, + { + "name": "one minute more", + "value": "150119987580m", + "whole": null, + "duration_ms": null + }, + { + "name": "the most hours", + "value": "2501999792h", + "whole": null, + "duration_ms": 9007199251200000 + }, + { + "name": "one hour more", + "value": "2501999793h", + "whole": null, + "duration_ms": null + }, + { + "name": "the most days", + "value": "104249991d", + "whole": null, + "duration_ms": 9007199222400000 + }, + { + "name": "one day more", + "value": "104249992d", + "whole": null, + "duration_ms": null + }, + { + "name": "five thousand nines of seconds", + "value": "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999s", + "whole": null, + "duration_ms": null + }, + { + "name": "U+0009 around a number, white space in both runtimes", + "value": "\t512\t", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000A around a number, white space in both runtimes", + "value": "\n512\n", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000B around a number, white space in both runtimes", + "value": "\u000b512\u000b", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000C around a number, white space in both runtimes", + "value": "\f512\f", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000D around a number, white space in both runtimes", + "value": "\r512\r", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+0020 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+00A0 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+1680 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2000 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2001 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2002 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2003 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2004 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2005 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2006 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2007 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2008 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2009 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+200A around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2028 around a number, white space in both runtimes", + "value": "
512
", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2029 around a number, white space in both runtimes", + "value": "
512
", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+202F around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+205F around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+3000 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+0009 around a duration, white space in both runtimes", + "value": "\t2d\t", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+00A0 around a duration, white space in both runtimes", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+2029 around a duration, white space in both runtimes", + "value": "
2d
", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+3000 around a duration, white space in both runtimes", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+001C around a number, white space in neither or in one runtime", + "value": "\u001c512\u001c", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001D around a number, white space in neither or in one runtime", + "value": "\u001d512\u001d", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001E around a number, white space in neither or in one runtime", + "value": "\u001e512\u001e", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001F around a number, white space in neither or in one runtime", + "value": "\u001f512\u001f", + "whole": null, + "duration_ms": null + }, + { + "name": "U+0085 around a number, white space in neither or in one runtime", + "value": "…512…", + "whole": null, + "duration_ms": null + }, + { + "name": "U+180E around a number, white space in neither or in one runtime", + "value": "᠎512᠎", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200B around a number, white space in neither or in one runtime", + "value": "​512​", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200C around a number, white space in neither or in one runtime", + "value": "‌512‌", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200D around a number, white space in neither or in one runtime", + "value": "‍512‍", + "whole": null, + "duration_ms": null + }, + { + "name": "U+2060 around a number, white space in neither or in one runtime", + "value": "⁠512⁠", + "whole": null, + "duration_ms": null + }, + { + "name": "U+FEFF around a number, white space in neither or in one runtime", + "value": "512", + "whole": null, + "duration_ms": null + } + ], + "switch_cases": [ + { + "name": "the boolean true", + "value": true, + "switch": true + }, + { + "name": "the boolean false", + "value": false, + "switch": false + }, + { + "name": "the text true", + "value": "true", + "switch": true + }, + { + "name": "the text false", + "value": "false", + "switch": false + }, + { + "name": "TRUE in upper case", + "value": "TRUE", + "switch": true + }, + { + "name": "FALSE in upper case", + "value": "FALSE", + "switch": false + }, + { + "name": "True with a capital", + "value": "True", + "switch": true + }, + { + "name": "False with a capital", + "value": "False", + "switch": false + }, + { + "name": "tRuE in mixed case", + "value": "tRuE", + "switch": true + }, + { + "name": "fAlSe in mixed case", + "value": "fAlSe", + "switch": false + }, + { + "name": "no value", + "value": null, + "switch": "default" + }, + { + "name": "an empty value", + "value": "", + "switch": "default" + }, + { + "name": "a blank value", + "value": " ", + "switch": null + }, + { + "name": "a space before true", + "value": " true", + "switch": null + }, + { + "name": "a space after true", + "value": "true ", + "switch": null + }, + { + "name": "a newline after false", + "value": "false\n", + "switch": null + }, + { + "name": "yes", + "value": "yes", + "switch": null + }, + { + "name": "no", + "value": "no", + "switch": null + }, + { + "name": "on", + "value": "on", + "switch": null + }, + { + "name": "off", + "value": "off", + "switch": null + }, + { + "name": "the text 1", + "value": "1", + "switch": null + }, + { + "name": "the text 0", + "value": "0", + "switch": null + }, + { + "name": "the letter t", + "value": "t", + "switch": null + }, + { + "name": "the letter f", + "value": "f", + "switch": null + }, + { + "name": "enabled", + "value": "enabled", + "switch": null + }, + { + "name": "maybe", + "value": "maybe", + "switch": null + }, + { + "name": "truefalse", + "value": "truefalse", + "switch": null + }, + { + "name": "the number 1", + "value": 1, + "switch": null + }, + { + "name": "the number 0", + "value": 0, + "switch": null + }, + { + "name": "the number 1.0", + "value": 1.0, + "switch": null + }, + { + "name": "a list holding true", + "value": [ + true + ], + "switch": null + }, + { + "name": "an empty list", + "value": [], + "switch": null + }, + { + "name": "a map", + "value": { + "value": true + }, + "switch": null + }, + { + "name": "fullwidth true", + "value": "true", + "switch": null + }, + { + "name": "true with a Cyrillic e", + "value": "truе", + "switch": null + }, + { + "name": "true with a dotted capital I after it", + "value": "trueİ", + "switch": null + } + ], + "time_cases": [ + { + "name": "a time in UTC to the second", + "text": "2026-11-20T10:00:00Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "a time in UTC to the millisecond", + "text": "2026-11-20T10:00:00.123Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a time in UTC to the minute", + "text": "2026-11-20T10:00Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "a fraction of one digit", + "text": "2026-11-20T10:00:00.1Z", + "ms": 1795168800100, + "stamp": "2026-11-20T10:00:00.100Z" + }, + { + "name": "a fraction of two digits", + "text": "2026-11-20T10:00:00.12Z", + "ms": 1795168800120, + "stamp": "2026-11-20T10:00:00.120Z" + }, + { + "name": "a fraction of six digits is cut after the third", + "text": "2026-11-20T10:00:00.123456Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a fraction of nine digits is cut after the third", + "text": "2026-11-20T10:00:00.123456789Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a fraction that would round up is cut", + "text": "2026-11-20T10:00:00.9996Z", + "ms": 1795168800999, + "stamp": "2026-11-20T10:00:00.999Z" + }, + { + "name": "a fraction of nine nines", + "text": "2026-11-20T23:59:59.999999999Z", + "ms": 1795219199999, + "stamp": "2026-11-20T23:59:59.999Z" + }, + { + "name": "a fraction of zeros", + "text": "2026-11-20T10:00:00.000Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "an offset ahead of UTC", + "text": "2026-11-20T10:00:00+01:00", + "ms": 1795165200000, + "stamp": "2026-11-20T09:00:00.000Z" + }, + { + "name": "an offset behind UTC", + "text": "2026-11-20T10:00:00-08:00", + "ms": 1795197600000, + "stamp": "2026-11-20T18:00:00.000Z" + }, + { + "name": "an offset of half an hour", + "text": "2026-11-20T10:00:00+05:30", + "ms": 1795149000000, + "stamp": "2026-11-20T04:30:00.000Z" + }, + { + "name": "an offset of three quarters of an hour", + "text": "2026-11-20T10:00:00.5+05:45", + "ms": 1795148100500, + "stamp": "2026-11-20T04:15:00.500Z" + }, + { + "name": "the largest offset ahead of UTC", + "text": "2026-11-20T10:00:00+23:59", + "ms": 1795082460000, + "stamp": "2026-11-19T10:01:00.000Z" + }, + { + "name": "the largest offset behind UTC", + "text": "2026-11-20T10:00:00-23:59", + "ms": 1795255140000, + "stamp": "2026-11-21T09:59:00.000Z" + }, + { + "name": "an offset of plus nothing", + "text": "2026-11-20T10:00:00+00:00", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "an offset of minus nothing", + "text": "2026-11-20T10:00:00-00:00", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "to the minute at an offset", + "text": "2026-11-20T10:00+01:00", + "ms": 1795165200000, + "stamp": "2026-11-20T09:00:00.000Z" + }, + { + "name": "an offset that crosses midnight into the year before", + "text": "2026-01-01T00:30:00+01:00", + "ms": 1767223800000, + "stamp": "2025-12-31T23:30:00.000Z" + }, + { + "name": "an offset that crosses midnight into the year after", + "text": "2026-12-31T23:30:00-01:00", + "ms": 1798763400000, + "stamp": "2027-01-01T00:30:00.000Z" + }, + { + "name": "an offset that crosses the 29th of February", + "text": "2024-03-01T00:00:00+00:01", + "ms": 1709251140000, + "stamp": "2024-02-29T23:59:00.000Z" + }, + { + "name": "midnight", + "text": "2026-11-20T00:00:00Z", + "ms": 1795132800000, + "stamp": "2026-11-20T00:00:00.000Z" + }, + { + "name": "the last second of a day", + "text": "2026-11-20T23:59:59Z", + "ms": 1795219199000, + "stamp": "2026-11-20T23:59:59.000Z" + }, + { + "name": "the 29th of February of a leap year", + "text": "2024-02-29T12:00:00Z", + "ms": 1709208000000, + "stamp": "2024-02-29T12:00:00.000Z" + }, + { + "name": "the 29th of February of the year 2000", + "text": "2000-02-29T12:00:00Z", + "ms": 951825600000, + "stamp": "2000-02-29T12:00:00.000Z" + }, + { + "name": "the 29th of February of the year 0004", + "text": "0004-02-29T12:00:00Z", + "ms": -62035848000000, + "stamp": "0004-02-29T12:00:00.000Z" + }, + { + "name": "the 31st of January", + "text": "2026-01-31T12:00:00Z", + "ms": 1769860800000, + "stamp": "2026-01-31T12:00:00.000Z" + }, + { + "name": "the 30th of April", + "text": "2026-04-30T12:00:00Z", + "ms": 1777550400000, + "stamp": "2026-04-30T12:00:00.000Z" + }, + { + "name": "the 31st of December", + "text": "2026-12-31T12:00:00Z", + "ms": 1798718400000, + "stamp": "2026-12-31T12:00:00.000Z" + }, + { + "name": "the first instant of 1970", + "text": "1970-01-01T00:00:00Z", + "ms": 0, + "stamp": "1970-01-01T00:00:00.000Z" + }, + { + "name": "an instant before 1970", + "text": "1969-12-31T23:59:59.250Z", + "ms": -750, + "stamp": "1969-12-31T23:59:59.250Z" + }, + { + "name": "a year before 1000", + "text": "0999-12-31T23:59:59Z", + "ms": -30610224001000, + "stamp": "0999-12-31T23:59:59.000Z" + }, + { + "name": "a year of two significant digits", + "text": "0033-04-03T15:00:00+02:00", + "ms": -61117758000000, + "stamp": "0033-04-03T13:00:00.000Z" + }, + { + "name": "the first instant both packs write", + "text": "0001-01-01T00:00:00Z", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant both packs write", + "text": "9999-12-31T23:59:59.999Z", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the last instant, with a longer fraction", + "text": "9999-12-31T23:59:59.999999999Z", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the first instant, written at an offset", + "text": "0001-01-01T00:01:00+00:01", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant, written at an offset", + "text": "9999-12-31T23:58:59.999-00:01", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the first instant, written a day later at the largest offset", + "text": "0001-01-01T23:59:00+23:59", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant, written a day earlier at the largest offset", + "text": "9999-12-31T00:00:59.999-23:59", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "no offset", + "text": "2026-11-20T10:00:00", + "ms": null, + "stamp": null + }, + { + "name": "no offset, to the minute", + "text": "2026-11-20T10:00", + "ms": null, + "stamp": null + }, + { + "name": "no offset, with a fraction", + "text": "2026-11-20T10:00:00.123", + "ms": null, + "stamp": null + }, + { + "name": "a date alone", + "text": "2026-11-20", + "ms": null, + "stamp": null + }, + { + "name": "a time alone", + "text": "10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a lower-case t", + "text": "2026-11-20t10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a lower-case z", + "text": "2026-11-20T10:00:00z", + "ms": null, + "stamp": null + }, + { + "name": "a space for the T", + "text": "2026-11-20 10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an underscore for the T", + "text": "2026-11-20_10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a space before", + "text": " 2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a space after", + "text": "2026-11-20T10:00:00Z ", + "ms": null, + "stamp": null + }, + { + "name": "a newline after", + "text": "2026-11-20T10:00:00Z\n", + "ms": null, + "stamp": null + }, + { + "name": "a carriage return and a newline after", + "text": "2026-11-20T10:00:00Z\r\n", + "ms": null, + "stamp": null + }, + { + "name": "a tab before", + "text": "\t2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a no-break space after", + "text": "2026-11-20T10:00:00Z ", + "ms": null, + "stamp": null + }, + { + "name": "a byte order mark before", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a next-line character after", + "text": "2026-11-20T10:00:00Z…", + "ms": null, + "stamp": null + }, + { + "name": "a NUL after", + "text": "2026-11-20T10:00:00Z\u0000", + "ms": null, + "stamp": null + }, + { + "name": "a space before the offset", + "text": "2026-11-20T10:00:00 +01:00", + "ms": null, + "stamp": null + }, + { + "name": "a space before the Z", + "text": "2026-11-20T10:00:00 Z", + "ms": null, + "stamp": null + }, + { + "name": "the basic format", + "text": "20261120T100000Z", + "ms": null, + "stamp": null + }, + { + "name": "the basic format of the time alone", + "text": "2026-11-20T100000Z", + "ms": null, + "stamp": null + }, + { + "name": "a week date", + "text": "2026-W47-5", + "ms": null, + "stamp": null + }, + { + "name": "a week date with a time", + "text": "2026-W47-5T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an ordinal date", + "text": "2026-324T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the hour alone", + "text": "2026-11-20T10Z", + "ms": null, + "stamp": null + }, + { + "name": "a comma for the point", + "text": "2026-11-20T10:00:00,5Z", + "ms": null, + "stamp": null + }, + { + "name": "a fraction of the minute", + "text": "2026-11-20T10:00.5Z", + "ms": null, + "stamp": null + }, + { + "name": "a point without digits", + "text": "2026-11-20T10:00:00.Z", + "ms": null, + "stamp": null + }, + { + "name": "a fraction of ten digits", + "text": "2026-11-20T10:00:00.1234567891Z", + "ms": null, + "stamp": null + }, + { + "name": "an offset in hours alone", + "text": "2026-11-20T10:00:00+01", + "ms": null, + "stamp": null + }, + { + "name": "an offset without its colon", + "text": "2026-11-20T10:00:00+0100", + "ms": null, + "stamp": null + }, + { + "name": "an offset with seconds", + "text": "2026-11-20T10:00:00+01:00:00", + "ms": null, + "stamp": null + }, + { + "name": "an offset of one digit an hour", + "text": "2026-11-20T10:00:00+1:00", + "ms": null, + "stamp": null + }, + { + "name": "an offset without a sign", + "text": "2026-11-20T10:00:0001:00", + "ms": null, + "stamp": null + }, + { + "name": "a zone's name after the offset", + "text": "2026-11-20T10:00:00+01:00[Europe/Paris]", + "ms": null, + "stamp": null + }, + { + "name": "a Z and an offset", + "text": "2026-11-20T10:00:00Z+01:00", + "ms": null, + "stamp": null + }, + { + "name": "two Zs", + "text": "2026-11-20T10:00:00ZZ", + "ms": null, + "stamp": null + }, + { + "name": "UTC for the Z", + "text": "2026-11-20T10:00:00UTC", + "ms": null, + "stamp": null + }, + { + "name": "GMT after a space", + "text": "2026-11-20T10:00:00 GMT", + "ms": null, + "stamp": null + }, + { + "name": "a date of the HTTP kind", + "text": "Fri, 20 Nov 2026 10:00:00 GMT", + "ms": null, + "stamp": null + }, + { + "name": "a date with slashes", + "text": "2026/11/20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a date with points", + "text": "2026.11.20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the day before the month", + "text": "20-11-2026T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a time with points", + "text": "2026-11-20T10.00.00Z", + "ms": null, + "stamp": null + }, + { + "name": "the seconds from 1970 in digits", + "text": "1795168800", + "ms": null, + "stamp": null + }, + { + "name": "the milliseconds from 1970 in digits", + "text": "1795168800000", + "ms": null, + "stamp": null + }, + { + "name": "a word", + "text": "yesterday", + "ms": null, + "stamp": null + }, + { + "name": "the word now", + "text": "now", + "ms": null, + "stamp": null + }, + { + "name": "empty text", + "text": "", + "ms": null, + "stamp": null + }, + { + "name": "a T alone", + "text": "T", + "ms": null, + "stamp": null + }, + { + "name": "two times", + "text": "2026-11-20T10:00:00Z2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a time and a word", + "text": "2026-11-20T10:00:00Z tomorrow", + "ms": null, + "stamp": null + }, + { + "name": "the 30th of February", + "text": "2026-02-30T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the 29th of February of a common year", + "text": "2026-02-29T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the 29th of February of the year 1900", + "text": "1900-02-29T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the 29th of February of the year 2100", + "text": "2100-02-29T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the 31st of April", + "text": "2026-04-31T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the 31st of November", + "text": "2026-11-31T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a month of nothing", + "text": "2026-00-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a thirteenth month", + "text": "2026-13-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a day of nothing", + "text": "2026-11-00T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a 32nd day", + "text": "2026-11-32T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "hour 24, minute nothing", + "text": "2026-11-20T24:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "hour 24", + "text": "2026-11-20T24:30:00Z", + "ms": null, + "stamp": null + }, + { + "name": "hour 25", + "text": "2026-11-20T25:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "minute 60", + "text": "2026-11-20T10:60:00Z", + "ms": null, + "stamp": null + }, + { + "name": "second 60, a leap second", + "text": "2026-12-31T23:59:60Z", + "ms": null, + "stamp": null + }, + { + "name": "second 61", + "text": "2026-11-20T10:00:61Z", + "ms": null, + "stamp": null + }, + { + "name": "an offset of 24 hours", + "text": "2026-11-20T10:00:00+24:00", + "ms": null, + "stamp": null + }, + { + "name": "an offset with 60 minutes", + "text": "2026-11-20T10:00:00+01:60", + "ms": null, + "stamp": null + }, + { + "name": "an offset of 99 hours", + "text": "2026-11-20T10:00:00-99:59", + "ms": null, + "stamp": null + }, + { + "name": "the year nothing", + "text": "0000-01-01T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the last day of the year nothing", + "text": "0000-12-31T23:59:59Z", + "ms": null, + "stamp": null + }, + { + "name": "the year nothing, at an offset that puts the instant in the year 0001", + "text": "0000-12-31T23:30:00-01:00", + "ms": null, + "stamp": null + }, + { + "name": "a year of five digits", + "text": "10000-01-01T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a year of six digits with a sign", + "text": "+002026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a year before nothing", + "text": "-0001-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a year of two digits", + "text": "26-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a year of three digits", + "text": "999-12-31T23:59:59Z", + "ms": null, + "stamp": null + }, + { + "name": "a month of one digit", + "text": "2026-1-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a day of one digit", + "text": "2026-11-2T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an hour of one digit", + "text": "2026-11-20T9:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a minute of one digit", + "text": "2026-11-20T10:0:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a second of one digit", + "text": "2026-11-20T10:00:0Z", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts before the year 0001", + "text": "0001-01-01T00:00:00+00:01", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts a day before the year 0001", + "text": "0001-01-01T23:58:59.999+23:59", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts past the year 9999", + "text": "9999-12-31T23:59:59-00:01", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts a day past the year 9999", + "text": "9999-12-31T00:01:00-23:59", + "ms": null, + "stamp": null + }, + { + "name": "Arabic-Indic digits in the year", + "text": "٢٠٢٦-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an Arabic-Indic digit in the second", + "text": "2026-11-20T10:00:0٠Z", + "ms": null, + "stamp": null + }, + { + "name": "fullwidth digits in the day", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth digit in the fraction", + "text": "2026-11-20T10:00:00.1Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth digit in the offset", + "text": "2026-11-20T10:00:00+01:00", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth colon", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth T", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth Z", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a minus sign of the mathematical kind in the offset", + "text": "2026-11-20T10:00:00−01:00", + "ms": null, + "stamp": null + }, + { + "name": "an en dash in the date", + "text": "2026–11–20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a superscript digit", + "text": "2026-11-20T10:00:0²Z", + "ms": null, + "stamp": null + }, + { + "name": "a lone surrogate after", + "text": "2026-11-20T10:00:00Z\ud800", + "ms": null, + "stamp": null + } + ], + "text_cases": [ + { + "name": "empty text", + "text": "", + "trimmed": "", + "blank": true + }, + { + "name": "a name", + "text": "order-assistant", + "trimmed": "order-assistant", + "blank": false + }, + { + "name": "a name with a space inside", + "text": "order assistant", + "trimmed": "order assistant", + "blank": false + }, + { + "name": "U+0009 alone, white space in both runtimes", + "text": "\t", + "trimmed": "", + "blank": true + }, + { + "name": "U+0009 around a name, white space in both runtimes", + "text": "\tname\t", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000A alone, white space in both runtimes", + "text": "\n", + "trimmed": "", + "blank": true + }, + { + "name": "U+000A around a name, white space in both runtimes", + "text": "\nname\n", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000B alone, white space in both runtimes", + "text": "\u000b", + "trimmed": "", + "blank": true + }, + { + "name": "U+000B around a name, white space in both runtimes", + "text": "\u000bname\u000b", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000C alone, white space in both runtimes", + "text": "\f", + "trimmed": "", + "blank": true + }, + { + "name": "U+000C around a name, white space in both runtimes", + "text": "\fname\f", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000D alone, white space in both runtimes", + "text": "\r", + "trimmed": "", + "blank": true + }, + { + "name": "U+000D around a name, white space in both runtimes", + "text": "\rname\r", + "trimmed": "name", + "blank": false + }, + { + "name": "U+0020 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+0020 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+00A0 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+00A0 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+1680 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+1680 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2000 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2000 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2001 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2001 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2002 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2002 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2003 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2003 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2004 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2004 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2005 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2005 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2006 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2006 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2007 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2007 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2008 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2008 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2009 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2009 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+200A alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+200A around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2028 alone, white space in both runtimes", + "text": "
", + "trimmed": "", + "blank": true + }, + { + "name": "U+2028 around a name, white space in both runtimes", + "text": "
name
", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2029 alone, white space in both runtimes", + "text": "
", + "trimmed": "", + "blank": true + }, + { + "name": "U+2029 around a name, white space in both runtimes", + "text": "
name
", + "trimmed": "name", + "blank": false + }, + { + "name": "U+202F alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+202F around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+205F alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+205F around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+3000 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+3000 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+001C alone, a character of a name", + "text": "\u001c", + "trimmed": "\u001c", + "blank": false + }, + { + "name": "U+001C around a name, a character of a name", + "text": "\u001cname\u001c", + "trimmed": "\u001cname\u001c", + "blank": false + }, + { + "name": "U+001D alone, a character of a name", + "text": "\u001d", + "trimmed": "\u001d", + "blank": false + }, + { + "name": "U+001D around a name, a character of a name", + "text": "\u001dname\u001d", + "trimmed": "\u001dname\u001d", + "blank": false + }, + { + "name": "U+001E alone, a character of a name", + "text": "\u001e", + "trimmed": "\u001e", + "blank": false + }, + { + "name": "U+001E around a name, a character of a name", + "text": "\u001ename\u001e", + "trimmed": "\u001ename\u001e", + "blank": false + }, + { + "name": "U+001F alone, a character of a name", + "text": "\u001f", + "trimmed": "\u001f", + "blank": false + }, + { + "name": "U+001F around a name, a character of a name", + "text": "\u001fname\u001f", + "trimmed": "\u001fname\u001f", + "blank": false + }, + { + "name": "U+0085 alone, a character of a name", + "text": "…", + "trimmed": "…", + "blank": false + }, + { + "name": "U+0085 around a name, a character of a name", + "text": "…name…", + "trimmed": "…name…", + "blank": false + }, + { + "name": "U+FEFF alone, a character of a name", + "text": "", + "trimmed": "", + "blank": false + }, + { + "name": "U+FEFF around a name, a character of a name", + "text": "name", + "trimmed": "name", + "blank": false + }, + { + "name": "U+180E alone, a character of a name", + "text": "᠎", + "trimmed": "᠎", + "blank": false + }, + { + "name": "U+180E around a name, a character of a name", + "text": "᠎name᠎", + "trimmed": "᠎name᠎", + "blank": false + }, + { + "name": "U+200B alone, a character of a name", + "text": "​", + "trimmed": "​", + "blank": false + }, + { + "name": "U+200B around a name, a character of a name", + "text": "​name​", + "trimmed": "​name​", + "blank": false + }, + { + "name": "U+200C alone, a character of a name", + "text": "‌", + "trimmed": "‌", + "blank": false + }, + { + "name": "U+200C around a name, a character of a name", + "text": "‌name‌", + "trimmed": "‌name‌", + "blank": false + }, + { + "name": "U+200D alone, a character of a name", + "text": "‍", + "trimmed": "‍", + "blank": false }, { - "name": "an older message landing late never overwrites a newer row, and an answer needs a recorded wait", - "steps": [ - { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1007-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1007", - "amount": 60.0, - "reason": "Damaged on arrival" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T11:00:00.000Z", - "expires_at": "2026-11-21T11:00:00.000Z", - "ticket": "v1.first.mac", - "link": "https://ask.example.test/ask/v1.first.mac" - }, - "now": "2026-11-19T11:00:00.200Z" - }, - { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1007-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1007", - "amount": 60.0, - "reason": "Damaged on arrival" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T10:59:00.000Z", - "expires_at": "2026-11-21T10:59:00.000Z", - "ticket": "v1.stale.mac", - "link": "https://ask.example.test/ask/v1.stale.mac" + "name": "U+200D around a name, a character of a name", + "text": "‍name‍", + "trimmed": "‍name‍", + "blank": false + }, + { + "name": "U+2060 alone, a character of a name", + "text": "⁠", + "trimmed": "⁠", + "blank": false + }, + { + "name": "U+2060 around a name, a character of a name", + "text": "⁠name⁠", + "trimmed": "⁠name⁠", + "blank": false + }, + { + "name": "U+0000 alone, a character of a name", + "text": "\u0000", + "trimmed": "\u0000", + "blank": false + }, + { + "name": "U+0000 around a name, a character of a name", + "text": "\u0000name\u0000", + "trimmed": "\u0000name\u0000", + "blank": false + }, + { + "name": "U+007F alone, a character of a name", + "text": "", + "trimmed": "", + "blank": false + }, + { + "name": "U+007F around a name, a character of a name", + "text": "name", + "trimmed": "name", + "blank": false + }, + { + "name": "every white-space character and nothing else", + "text": "\t\n\u000b\f\r              

   ", + "trimmed": "", + "blank": true + }, + { + "name": "every white-space character around a name", + "text": "\t\n\u000b\f\r              

   name\t\n\u000b\f\r              

   ", + "trimmed": "name", + "blank": false + }, + { + "name": "white space before a name only", + "text": " \t name", + "trimmed": "name", + "blank": false + }, + { + "name": "white space after a name only", + "text": "name\r\n", + "trimmed": "name", + "blank": false + }, + { + "name": "white space inside a name is kept", + "text": " order assistant ", + "trimmed": "order assistant", + "blank": false + }, + { + "name": "a byte order mark inside white space", + "text": "  ", + "trimmed": "", + "blank": false + }, + { + "name": "white space inside two byte order marks", + "text": " ", + "trimmed": " ", + "blank": false + }, + { + "name": "a next-line character after white space", + "text": "name …", + "trimmed": "name …", + "blank": false + }, + { + "name": "a unit separator before white space", + "text": "\u001f name", + "trimmed": "\u001f name", + "blank": false + }, + { + "name": "fifty spaces", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "a name between fifty spaces", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "a lone surrogate between spaces", + "text": " \ud800 ", + "trimmed": "\ud800", + "blank": false + } + ], + "exact_cases": [ + { + "name": "whole numbers past 9007199254740991 in a waiting call's input and in a decision", + "message": { + "kind": "approval", + "graph_id": "ledger-assistant", + "description": "Ledger assistant: a transfer waits for a controller", + "correlation_id": "transfer-88-case", + "turn": 4, + "node": "assist", + "summary": "transfer_units from ACC-7: more units than a double counts exactly", + "calls": [ + { + "id": "toolu_01A", + "name": "transfer_units", + "route": "demo.units.transfer", + "wait": true, + "input": { + "account": "ACC-7", + "units": null, + "limits": [ + null, + null + ], + "counter": null, + "note": "café 
 \"quoted\"" + } }, - "now": "2026-11-19T11:00:00.300Z", - "note": "a message older than the row lands late (two recorder workers, or a redelivery): the row stands and the sequence does not move" - }, + { + "id": "toolu_02B", + "name": "ask_controller", + "ask": true, + "wait": true, + "input": { + "question": "How many units?" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "numbers": [ { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1007-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1007", - "amount": 60.0, - "reason": "Damaged on arrival" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T11:05:00.000Z", - "expires_at": "2026-11-21T11:05:00.000Z", - "ticket": "v1.newer.mac", - "link": "https://ask.example.test/ask/v1.newer.mac" - }, - "now": "2026-11-19T11:05:00.100Z", - "note": "a newer re-advice updates the row with its ticket" + "place": [ + "calls", + 0, + "input", + "units" + ], + "digits": "1152921504606846977" }, { - "op": "answer", - "key": [ - "order-assistant", - "order-1007-case", - 2 - ], - "decisions": [ - { - "id": "toolu_01A", - "approved": true - } + "place": [ + "calls", + 0, + "input", + "limits", + 0 ], - "who": "operator-17", - "status": 200, - "body": { - "type": "answer", - "turn": 3 - }, - "now": "2026-11-19T11:06:00.000Z" + "digits": "-9223372036854775808" }, { - "op": "answer", - "key": [ - "order-assistant", - "order-9999-case", - 7 - ], - "decisions": [ - { - "id": "toolu_09Z", - "approved": true - } + "place": [ + "calls", + 0, + "input", + "limits", + 1 ], - "who": "operator-17", - "status": 200, - "body": { - "type": "answer", - "turn": 8 - }, - "now": "2026-11-19T11:06:30.000Z", - "note": "an answer for a wait that was never recorded: nothing to write, the result is null" + "digits": "9223372036854775807" }, { - "op": "since", - "seq": 0, - "limit": 10 + "place": [ + "calls", + 0, + "input", + "counter" + ], + "digits": "18446744073709551615" } ], - "results": [ - { - "id": 1, - "seq": 1, - "state": "open", - "ticket": "v1.first.mac" - }, - { - "id": 1, - "seq": 1, - "state": "open", - "ticket": "v1.first.mac" - }, - { - "id": 1, - "seq": 2, - "state": "open", - "ticket": "v1.newer.mac" - }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "ticket": "v1.eyJjIjoidHJhbnNmZXItODgtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJsZWRnZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6NH0.uPkPasxUhzLey3qmHCPX08Qh_nDHJfxhfM6JFoRmu0Q", + "expires_at": "2026-11-21T09:12:04.118Z", + "record": "{\"kind\":\"approval\",\"graph_id\":\"ledger-assistant\",\"description\":\"Ledger assistant: a transfer waits for a controller\",\"correlation_id\":\"transfer-88-case\",\"turn\":4,\"node\":\"assist\",\"summary\":\"transfer_units from ACC-7: more units than a double counts exactly\",\"calls\":[{\"id\":\"toolu_01A\",\"name\":\"transfer_units\",\"route\":\"demo.units.transfer\",\"wait\":true,\"input\":{\"account\":\"ACC-7\",\"units\":1152921504606846977,\"limits\":[-9223372036854775808,9223372036854775807],\"counter\":18446744073709551615,\"note\":\"café 
 \\\"quoted\\\"\"}},{\"id\":\"toolu_02B\",\"name\":\"ask_controller\",\"ask\":true,\"wait\":true,\"input\":{\"question\":\"How many units?\"}}],\"ttl\":\"2d\",\"requested_at\":\"2026-11-19T09:12:04.118Z\",\"expires_at\":\"2026-11-21T09:12:04.118Z\",\"ticket\":\"v1.eyJjIjoidHJhbnNmZXItODgtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJsZWRnZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6NH0.uPkPasxUhzLey3qmHCPX08Qh_nDHJfxhfM6JFoRmu0Q\",\"link\":\"https://ask.example.test/ask/v1.eyJjIjoidHJhbnNmZXItODgtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJsZWRnZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6NH0.uPkPasxUhzLey3qmHCPX08Qh_nDHJfxhfM6JFoRmu0Q\"}", + "decisions": [ { - "id": 1, - "seq": 3, - "state": "answered", - "answered_by": "operator-17" + "id": "toolu_01A", + "approved": true, + "note": "counted twice" }, - null, { - "ids": [ - 1 - ], - "seqs": [ - 3 - ] + "id": "toolu_02B", + "answer": null } ], - "final": [ + "decision_numbers": [ { - "id": 1, - "seq": 3, - "kind": "approval", - "state": "answered", - "ticket": "v1.newer.mac", - "turn": 2, - "requested_at": "2026-11-19T11:05:00.000Z", - "expires_at": "2026-11-21T11:05:00.000Z", - "updated_at": "2026-11-19T11:06:00.000Z", - "answered_by": "operator-17", - "outcome": { - "status": 200, - "body": { - "type": "answer", - "turn": 3 - } - } + "place": [ + 1, + "answer" + ], + "digits": "9007199254740993" } - ] + ], + "decisions_record": "[{\"id\":\"toolu_01A\",\"approved\":true,\"note\":\"counted twice\"},{\"id\":\"toolu_02B\",\"answer\":9007199254740993}]" } ] } From e978c96a775a55626d18889654ea3f938eb3a799 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:04 -0800 Subject: [PATCH 5/5] docs(changelog): the loose-ends round - the agent tools, the LLM helper, ask-person and agent-question, the YAML 1.2.2 reader, REST automation and the host Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 178 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 138 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb8d9c1..16b2738 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -242,6 +242,44 @@ choose it as deployment configuration and give it only what a graph may show a model. **Upgrade note:** none without `attachments`; a call without the field reads no folder and sends text as before. +13. **REST automation: `rest.yaml` as the router of a Python application (RFC-0018 in mercury-composable, build + plan step 1).** With `rest.automation: true` the host reads one `yaml.rest.automation` location (default + `classpath:/rest.yaml`, the `resources/rest.yaml` next to the application file; `file:` an absolute path) in the + engines' grammar and serves its entries on the one server: a URL and its methods mapped to a function, which + receives the whole request as the engines' `AsyncHttpRequest` map (the class is exported for reading it); CORS + blocks with the preflight; request and response header transforms; an `authentication` function whose `true` + verdict lets the request through and whose headers ride as the session map; the entry's `timeout` riding the + request as `x-ttl` (an inbound one wins) and answering 408; `tracing` from a W3C `traceparent`, the trace-id + header or a fresh id with the per-entry header-name overrides, leaving the edge's `http.request` record and the + function's round-trip record as the engines leave them; the correlation id always ensured, delivered as + `my_correlation_id` and echoed on the response; the request body parsed by its declared content type, repeated + query parameters as a list, cookies as a map; the response content type the function's or negotiated from + `Accept`, a failure as the standard error body, a returned envelope setting the status and headers; + `stream: true` rendering an interceptor's segments as Server-Sent Events or chunked text; `POST /api/event` and + the actuators as the engines' default entries a user entry may override; the `static-content` block's + `no-cache-pages` and `filter` over the static folder. An entry whose function is not registered at the end of + the boot is skipped with the engines' warning, never a live URL. Refused by name at load, so the grammar shows the + scope fence: a flow binding, the HTTP relay, the A/B dual service and `upload`; deferred as in the Rust port: + `custom.content.types`, `mime.types` and XML. Off by default: without the switch the host is unchanged. Pinned + by `tests/vectors/rest-automation-vectors.json` (new, 126 cases over the pure half, shared with the Node pack) + and the 45 tests of `tests/test_rest_automation.py` over HTTP; the demo app gains `hello.rest` at + `GET /api/hello/{name}` with its `resources/rest.yaml`. No new dependency. + +14. **Upload in REST automation, and the LLM helper's document intake (RFC-0018; Eric's direction of 2026-11-25: + documents uploaded to the helper for a model to read).** `upload: true` on a `POST` entry is the pack's bounded form + of the engines' streaming upload: the files of a `multipart/form-data` body arrive in the request map under the + engines' keys (`filename`, `file_type`, `file_length`, the `upload` tags, `size`) with their bytes in `contents` - + the stream routes the engines send replaced by the bytes - all together within `rest.upload.max.bytes` (16 MiB; a + 413 the moment they exceed it), the form's text fields as query parameters, the body absent; a non-multipart body + on such an entry dispatches as usual. `AsyncHttpRequest.files()` reads them as `UploadedFile` (name, content type, + size, tag, bytes), both exported. The LLM helper gains `llm.upload` behind `POST /api/llm/upload` + (`resources/rest.yaml`, `rest.automation: true` in its `application.yml`): each file is saved under `uploads/` + inside `llm.attachments.root` under a new name and the references returned - the `path` a later `llm.chat` call + names in `attachments`, the kind by the first bytes, the size, the SHA-256 the audit keeps and `attachable`, + whether the model takes the file as it is or a conversion comes first. Pinned by the vector file at version 2 + (an upload entry accepted, the request map and the accessors with the bytes as base64 in the file), four tests + over HTTP and `tests/test_llm_upload.py`. The host's static-content rules and the rest of the edge are unchanged. + ### Fixed 1. **The agent-question app keeps the first accepted decision when two devices decide one card at the same moment** @@ -360,43 +398,103 @@ or `false`. A text field of an upload counts toward `rest.upload.max.bytes` by its bytes, so a long field in another script counts for more than before. -13. **REST automation: `rest.yaml` as the router of a Python application (RFC-0018 in mercury-composable, build - plan step 1).** With `rest.automation: true` the host reads one `yaml.rest.automation` location (default - `classpath:/rest.yaml`, the `resources/rest.yaml` next to the application file; `file:` an absolute path) in the - engines' grammar and serves its entries on the one server: a URL and its methods mapped to a function, which - receives the whole request as the engines' `AsyncHttpRequest` map (the class is exported for reading it); CORS - blocks with the preflight; request and response header transforms; an `authentication` function whose `true` - verdict lets the request through and whose headers ride as the session map; the entry's `timeout` riding the - request as `x-ttl` (an inbound one wins) and answering 408; `tracing` from a W3C `traceparent`, the trace-id - header or a fresh id with the per-entry header-name overrides, leaving the edge's `http.request` record and the - function's round-trip record as the engines leave them; the correlation id always ensured, delivered as - `my_correlation_id` and echoed on the response; the request body parsed by its declared content type, repeated - query parameters as a list, cookies as a map; the response content type the function's or negotiated from - `Accept`, a failure as the standard error body, a returned envelope setting the status and headers; - `stream: true` rendering an interceptor's segments as Server-Sent Events or chunked text; `POST /api/event` and - the actuators as the engines' default entries a user entry may override; the `static-content` block's - `no-cache-pages` and `filter` over the static folder. An entry whose function is not registered at the end of - the boot is skipped with the engines' warning, never a live URL. Refused by name at load, so the grammar shows the - scope fence: a flow binding, the HTTP relay, the A/B dual service and `upload`; deferred as in the Rust port: - `custom.content.types`, `mime.types` and XML. Off by default: without the switch the host is unchanged. Pinned - by `tests/vectors/rest-automation-vectors.json` (new, 126 cases over the pure half, shared with the Node pack) - and the 45 tests of `tests/test_rest_automation.py` over HTTP; the demo app gains `hello.rest` at - `GET /api/hello/{name}` with its `resources/rest.yaml`. No new dependency. - -14. **Upload in REST automation, and the LLM helper's document intake (RFC-0018; Eric's direction of 2026-11-25: - documents uploaded to the helper for a model to read).** `upload: true` on a `POST` entry is the pack's bounded form - of the engines' streaming upload: the files of a `multipart/form-data` body arrive in the request map under the - engines' keys (`filename`, `file_type`, `file_length`, the `upload` tags, `size`) with their bytes in `contents` - - the stream routes the engines send replaced by the bytes - all together within `rest.upload.max.bytes` (16 MiB; a - 413 the moment they exceed it), the form's text fields as query parameters, the body absent; a non-multipart body - on such an entry dispatches as usual. `AsyncHttpRequest.files()` reads them as `UploadedFile` (name, content type, - size, tag, bytes), both exported. The LLM helper gains `llm.upload` behind `POST /api/llm/upload` - (`resources/rest.yaml`, `rest.automation: true` in its `application.yml`): each file is saved under `uploads/` - inside `llm.attachments.root` under a new name and the references returned - the `path` a later `llm.chat` call - names in `attachments`, the kind by the first bytes, the size, the SHA-256 the audit keeps and `attachable`, - whether the model takes the file as it is or a conversion comes first. Pinned by the vector file at version 2 - (an upload entry accepted, the request map and the accessors with the bytes as base64 in the file), four tests - over HTTP and `tests/test_llm_upload.py`. The host's static-content rules and the rest of the edge are unchanged. +8. **The agent tools: one reader of a URL and of `robots.txt` in both packs, a search by regular expression that + ends at a bound, and settings read by one rule.** The web tools read a URL with each runtime's own reader, and + 103 of 210 probe URLs came out differently in the two packs: `http://0177.0.0.1/` was kept here and was + 127.0.0.1 in the Node.js twin, and one page was fetched once for each spelling of its link. Both packs now take + a URL apart by one set of rules and write it back in one form - `http` or `https`, no credentials, a host that is + a name, an IPv4 address in dotted decimal or an IPv6 address in brackets, a port in the digits 0 to 9, the path + and the query percent-encoded one way and without `.` and `..` segments, at most 8192 characters - refuse + anything else by name, and ask a site for exactly what was checked. `robots.txt` is read by the tools' own + RFC 9309 reader in place of `urllib.robotparser`, whose answers changed with the Python version, and a rule is + matched part by part between its stars, so its time is bounded by its length plus the path's. `file.search` with `regex: true` runs the expression in a child + interpreter that is ended at `tools.file.search.timeout.ms` (10 s by default) with a 408 - `(a+)+$` against + forty letters did not finish, with the event loop held - and a literal is a substring test in the host. Smaller: + a byte-order mark at the start of a text is no part of it; a walk looks at 20,000 entries at most and says + `truncated`; the port of an allowlist entry and a page number are the digits 0 to 9; a number argument above + 9007199254740991 is a 400; a `tools.*` setting that is no number or no switch stops the start by name. + **Upgrade note:** a host outside letters, digits, hyphen, dot and underscore is refused, so an internationalized + name is written in its `xn--` form; a URL in a result is in the one form and may be spelled differently than + before; a switch written `yes`, `on` or `1`, and a number written with a sign or an underscore, stop the start; a workspace of more than 20,000 entries is listed and searched up to there; a search by regular + expression starts one interpreter, about 55 ms, and answers a 408 at its bound. + +9. **The LLM helper reads its settings when it starts, and a switch, a time in milliseconds and a page list by one + rule.** A wrong `llm.provider`, `llm.backend`, `llm.max.tokens`, `llm.timeout.ms`, `llm.max.retries`, + `llm.effort`, `llm.fallbacks`, `llm.transcript.ttl` or `llm.transcript.retention` was refused by the first + request that needed it. A start-up step now reads them, and builds the transcript store when one is named, so a + wrong one stops the application by name (`llm.helper cannot start - llm.max.tokens must be a whole number >= 1`); + the attachment limits and the audit's sweep and switches are read by their own steps. A switch + (`llm.log.batches`, `llm.transcript.audit.single`, the two `ssl` keys) is `true` or `false`: `yes`, `on` and `1` + were read as off without a word - TLS written `yes` was no TLS - and now stop the start. A time in milliseconds + is at most 2147483647, the longest wait the Node.js twin's timers hold; the audit's retention is at most + `1000000d`, since a longer one overflowed the expiry's date in the closing turn; a port is at most 65535. In a + page list white space is ignored around a number and refused inside one: `"1 3"` was page 13. A path is blank + by the same 24 characters in both packs. An attachment is read a mebibyte at a time: one read of the whole + allowance was a `MemoryError` under a very large `llm.attachments.max.bytes`. The shared vectors gain `switches` + (22 values) and `start` (47 cases). **Upgrade note:** a deployment with a wrong value it never exercised no + longer starts; `llm.transcript.store: redis` without its client stops the start, where it was a 503 on the first + loop turn; an empty `llm.transcript.audit.postgres.ssl` is its default, TLS on, where it was off; `"1 3"` as + pages is a 400. + +10. **ask-person and agent-question: one reader of a time, a number, a duration and a switch, a signed payload with + one spelling, and a wait that always has an expiry both packs can write.** A time without an offset was UTC + here and local time in the Node.js twin, and each pack took spellings the other refused; a time is now a date, + `T`, a time to the minute or the second, and `Z` or an offset, read to the millisecond by one rule, for + `requested_at`, a wait's `expires_at` at the intake and the transcripts' `before`. A `ttl` whose expiry is past + the year 9999 was an unhandled `OverflowError`; it is a 400, `ttl must end before the year 10000`. `turn`, `ttl`, + `GET /questions`' `since`, `before` and `limit`, and every setting follow the number and duration rule, where + digits of another script were taken here and a 5,000-digit value raised; a switch that is neither `true` nor + `false` stops the boot, where `ask.enabled: yes` was on and `ask.audit.postgres.ssl: no` was read as on. The + bytes under a ticket's signature must be the canonical JSON of its five fields: both packs took other spellings, + and agree with a reference on 200,074 generated payloads now. A `graph_id` or `correlation_id` with a lone + surrogate raised `UnicodeEncodeError` and is a 400. A setting that sets a timer is at most 2147483647 ms, a + port at most 65535, a `turn` at most 2147483647, the record's column; a required text is blank by the same 24 + characters in both packs; a bearer token with a character past ASCII raised `TypeError` and is compared by its + bytes. **Upgrade note:** a time without an offset, with white space around it or with a lower-case `t` or `z` is + a 400; `"2 d"` with a space before its unit is refused; `ask.enabled` and the `ssl` switches take `true` or + `false` only, and an empty `ask.enabled` is its default, on, where it was off; a ticket minted outside the packs + with another JSON spelling is malformed; `turn` as text digits (`"2"`) is taken. + +11. **Every YAML file is read by YAML 1.2.2 in both packs, and a setting of the host by one rule (the maintainer's + ruling of 2026-11-29).** The configuration file was read by each pack's YAML library - PyYAML reads YAML 1.1, + the Node.js twin's library YAML 1.2 - and 130 of 239 probe scalars came out differently through the two packs: + `yes` was a boolean here and text there, `010` was 8 and 10, `16_000` and `1:30` were numbers here only, `1e3` a + number there only, a date a `datetime.date`, and the text of a boolean `True`. One reader per pack now resolves + a plain scalar by the core schema of YAML 1.2.2: `true` and `false` are the booleans, `010` is 10, `0o10` is 8, + and `yes`, `on`, `16_000`, `1:30`, `0b101`, a date and the merge key are text or an ordinary key. It reads + `application.yml`, `rest.yaml`, `app-log-context.yaml` and the MCP binding's file; a reference written from the + specification agrees with both packs on 239 probes, and on 126,316 generated scalars but for what the two + parsers take differently before a scalar is resolved. As text a boolean is `true` or `false` and a float keeps + its point. A key with no value takes its default, and so does one whose references leave it empty + (`'${NAME:}'`), as in the Java engine; a `${key}` reference sees a `-D` or `set` override; a reference that + leads back to itself is logged and has no value, where it was a `RecursionError`. A setting of the host that is + no number, no duration or no switch stops the start by name instead of being read as a default or as off: + `rest.automation`, `rest.server.port`, `rest.upload.max.bytes`, `event.stream.keep.alive`, an entry's `timeout`, + `otel.forwarding` and `app.log.context`. The guides say how a file is read and recommend YAML 1.2.2 to whoever + writes one - a developer or an AI assistant - with the spellings the Java engine's YAML 1.1 reader takes + another way (Configuration Reference, the AI agent guide's checklist, `llms.txt`). **Upgrade note:** in a + file, `yes`, `no`, `on` and `off` are text, so a switch or a flag written that way stops the start - write + `true` or `false`; `010` is 10, not 8; `16_000`, `1:30` and `0b101` are text; `<<` merges nothing; a file with + a tag such as `!!binary` or `!!timestamp` does not load. An entry's `timeout` of `5 s`, `-5s` or a word stops + the start, where it was 5 s or the default, and `1h` is an hour held to the five-minute cap, where it was the + default. `get_property` of a boolean is `true`, not `True`. + +12. **REST automation and the host: an upload is read by the pack's own reader, the same in both packs, and an + edge failure is the failure the caller sees.** The two packs read a `multipart/form-data` body with their web + framework's reader and differed on a file without a content type, a first field named `_charset_` (a 500 page + here), a field that is not UTF-8, a declared ISO-8859-1, a part without a name, an empty filename and a + transfer encoding. `parse_upload` now reads the body in both packs, pinned by 76 shared cases that run over the + reader and over HTTP: a file without a content type is `application/octet-stream`; a text field is UTF-8, or + the ISO-8859-1 or US-ASCII its part declares; `filename*` and `name*` are taken as RFC 5987 writes them, which + some HTTP clients send for a name that is not ASCII; a part whose transfer or content encoding + changes its bytes is refused by name. The client's `request()` and `send()` return an edge's JSON error as the + failure it carries, as `stream()` did, where they raised `Invalid event-over-http response`. A reply the wire + codec refuses on `POST /api/event`, and a static-content filter's reply that cannot be rendered, are the + engines' 500 `Reply cannot be rendered`, where they were the web framework's own page with the edge recorded + at 200. A traced request the edge refuses while it reads the body - a 400, a 413 - leaves its record, as the + Java engine's edge does. An `x-ttl` is a whole number or counts as none. **Upgrade note:** a part with + `Content-Transfer-Encoding: base64` was decoded and is refused, and so is a part with a content encoding, + whose bytes were cut at 256 KiB without a word. ### Changed @@ -439,12 +537,12 @@ 4. **The agent-question app generates no page: `GET /questions/app` is retired.** The React UI's bundle at the root replaces the vanilla page (Added 9). **Upgrade note:** open `http://127.0.0.1:8092/` instead of `/questions/app`. -2. **`web.crawl` accepts a relative `include`.** A prefix that does not start with `/` now matches anywhere in a link's path, +5. **`web.crawl` accepts a relative `include`.** A prefix that does not start with `/` now matches anywhere in a link's path, since a model names a section as `guides/` as often as `/guides/`: the live drive of the Playground's `site-notes` graph showed a crawl returning the start page alone because the model's `include` was relative. The README's Event-over-HTTP example lists one route per entry - the engines' map takes no comma-separated list. -2. **A `-D` override value is resolved with the same `${ENV_VAR:default}` substitution as a file value - the engines' +6. **A `-D` override value is resolved with the same `${ENV_VAR:default}` substitution as a file value - the engines' change of the same day.** `AppConfig.get` returned an override as written, so a key moved from `application.yml` to a `-D` flag silently lost its substitution and a credential had to travel on the command line in clear. Now the value of a `-D` override (and of `AppConfig.set`) - an environment variable with a default, or a reference to another @@ -453,7 +551,7 @@ **Upgrade note:** a `-D` value that relied on a literal `${...}` is now resolved, as a file value always was; an unresolved reference without a default is no value, as in a file. -2. **The transcript audit store's PostgreSQL pool sets a server-side `statement_timeout` from +7. **The transcript audit store's PostgreSQL pool sets a server-side `statement_timeout` from `llm.transcript.audit.postgres.timeout.ms`.** The live drive of 2026-11-17 (mercury-composable `docs/test-reports/transcript-audit-live-drive.md`) showed a stopped database failing a write by type within the connection timeout, as designed, but a paused one - a TCP black hole - holding the pooled connection's statement, and