Sfoglia il codice sorgente

feat: an error-handler trigger, and release 0.15.0

A function can now declare `type: 'error'` and run when ANOTHER function
fails. Like a job it has no route and no schedule and cannot be called
directly, so declaring one publishes no endpoint and nobody can fake an
alert. `watch` names the function whose failures it answers, defaulting to
every function in the project.

THE LOOP GUARD IS CATEGORICAL, NOT A DEPTH BUDGET, and that is the decision
to understand before touching this. A failing error handler triggers
nothing - not itself, and not a different handler. A depth limit is right
for db triggers, where chaining is legitimate and only runaway chaining is
not, but there is no legitimate reason to report the failure of a failure
reporter, and two handlers both watching * would ping-pong under any budget
above zero. The shape prevented: a handler that e-mails an alert, fails
because egress is denied, and triggers itself forever on the tenant's own
queue. The cost is stated in the docs rather than glossed over - a handler's
own failures are visible only in the run log.

Other decisions:

- Handlers are ENQUEUED, not run inline, so a failing request never waits on
  the handler reporting it and a slow handler cannot hold the socket of a
  request that already went wrong. Delivery is at-least-once, so a handler
  must be idempotent.
- `watch` is matched exactly, no globbing beyond a bare `*`. A prefix match
  would quietly start catching functions added later, and a handler widening
  its own scope is the opposite of what an operator wants from one.
- Dispatch hangs off the same point as the run-log append, as ONE
  implementation called from both producers rather than four lines inlined
  at each - this codebase has already paid for calling unknownKeys() in one
  handler while six siblings stayed broken.
- Best-effort and never throws: a function that failed AND could not enqueue
  its handler must still report its own failure.
- The invoke route can invoke any trigger type, so the failed type is read
  from the stored row rather than assumed, and an unparseable descriptor
  defaults to Error, which SUPPRESSES dispatch - failing closed costs a
  missed alert on a function that is invalid anyway, failing open risks a
  loop.
- An empty `watch` is refused rather than read as `*`: it is almost always an
  unsubstituted template, and reading it as "everything" would wire up a
  handler the author never asked for.

17 tests, and both guards falsified: removing the categorical guard turns
the loop test red, and removing the self-selection guard turns a second one
red. The pairing is that an error handler is NOT matchable as an HTTP route
even if its row carries one.

VERSION and openapi info.version move together to 0.15.0. This supersedes
0.14.0, which was built but never published, so no version number is reused
for different content - 0.15.0 carries 0.14.0's two fixes as well as these.

Also updates the regex filter docs now that database 2.20.0 ships RE2: the
paragraph is split by version rather than rewritten, because the deployed
server is still 2.17.2 and the old behaviour is what a caller observes
today. Branch on the re2_regex_filters capability, not on a version string.

Suite 1325/1325 serially, against a 2.20.0 database.
fszontagh 1 mese fa
parent
commit
59f43e18c4

+ 4 - 1
CLAUDE.md

@@ -99,7 +99,10 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A write is validated on a runner before storage**, so the engine that validates is the engine that executes; with no healthy runner the write is refused **503** rather than stored unchecked.
 - **A write is validated on a runner before storage**, so the engine that validates is the engine that executes; with no healthy runner the write is refused **503** rather than stored unchecked.
 - **`RunnerPool` retry is three-way, not two.** Never connected → retry (nothing ran). Answered, whatever the answer → never retry (the runner did its job). **Delivered then unanswered** (read timeout, non-200, unparseable body) → **do not retry**, mark unhealthy: the handler may be running right now, and a retry would run a side-effecting function twice. `validate()` retries everything, because compiling has no side effects. Also: `RunnerPool::Options::readTimeoutSec` **must exceed** the runner's `max_wall_time_ms`, or our read times out before the runner can report its own timeout and the caller gets a misleading 503 instead of a 504.
 - **`RunnerPool` retry is three-way, not two.** Never connected → retry (nothing ran). Answered, whatever the answer → never retry (the runner did its job). **Delivered then unanswered** (read timeout, non-200, unparseable body) → **do not retry**, mark unhealthy: the handler may be running right now, and a retry would run a side-effecting function twice. `validate()` retries everything, because compiling has no side effects. Also: `RunnerPool::Options::readTimeoutSec` **must exceed** the runner's `max_wall_time_ms`, or our read times out before the runner can report its own timeout and the caller gets a misleading 503 instead of a 504.
 - **`ctx.collections(...)` is a direct gateway call, never loopback HTTP**, and `ctx.fetch` pins the connection to the single address the guard approved (`set_hostname_addr_map`) rather than re-resolving - re-resolving IS the rebinding window. One resolution, one classification.
 - **`ctx.collections(...)` is a direct gateway call, never loopback HTTP**, and `ctx.fetch` pins the connection to the single address the guard approved (`set_hostname_addr_map`) rather than re-resolving - re-resolving IS the rebinding window. One resolution, one classification.
-- **Triggers:** `http` (a route), `cron` (a schedule, with an IANA `tz` validated against the host tz database at PUSH time - an unknown zone is refused, never silently UTC), `db` (an INSERT/UPDATE/DELETE on a watched collection) and `job` (reached only by being enqueued, which is where slow work belongs). The scheduler and the event watcher live in **vectorapi**, because there must be exactly one of each; N runners each firing every cron is the obvious bug.
+- **Triggers:** `http` (a route), `cron` (a schedule, with an IANA `tz` validated against the host tz database at PUSH time - an unknown zone is refused, never silently UTC), `db` (an INSERT/UPDATE/DELETE on a watched collection) `job` (reached only by being enqueued, which is where slow work belongs) and **`error`** (0.15.0+, runs when ANOTHER function fails). The scheduler and the event watcher live in **vectorapi**, because there must be exactly one of each; N runners each firing every cron is the obvious bug.
+- **THE `error` TRIGGER'S LOOP GUARD IS CATEGORICAL, NOT A DEPTH BUDGET, AND THAT IS THE ONE DECISION TO UNDERSTAND BEFORE TOUCHING IT.** `selectErrorHandlers()` (`functions/error_hook.hpp`, pure) returns NOTHING when the failed function is itself an error handler - not itself, and not a different handler. A depth limit would be wrong here in a way it is not wrong for `db` triggers: chaining db events is legitimate and only runaway chaining is not, whereas there is no legitimate reason to report the failure of a failure reporter. The shape being prevented is a handler that tries to e-mail an alert, fails because egress is denied, and triggers itself forever on the tenant's own queue - and two handlers both watching `*` would ping-pong indefinitely under any budget above zero. **The cost is real and must be stated to anyone relying on it: an error handler's own failures are visible ONLY in the run log**, so "the alerts stopped" is a run-log question.
+  Three more decisions worth keeping. **Handlers are ENQUEUED rather than run inline**, so a failing request never waits on the handler reporting it and a slow handler cannot hold the socket of a request that already went wrong - which also means delivery is at-least-once and a handler must be idempotent. **`watch` is matched exactly with no globbing beyond a bare `*`**, because a prefix match would quietly start catching functions added later, and a handler widening its own scope is the opposite of what an operator wants. And **dispatch hangs off the same point as the run-log append** (`dispatchErrorHandlers`, one implementation called from both producers) rather than being inlined at each site, because this file already records what happened when `unknownKeys()` was called in one handler while six siblings stayed broken - a new producer of failed runs should call it rather than grow a third copy. It is best-effort and never throws: a function that failed AND could not enqueue its handler must still report its own failure.
+  Note the invoke route can invoke a function of ANY trigger type, so the failed type is read from the stored row rather than assumed, and **an unparseable descriptor defaults to `Error`, which SUPPRESSES dispatch** - failing closed costs a missed alert on a function that is invalid anyway, while failing open risks a loop.
 - **A blocking host call cannot be interrupted, so host timeouts ARE the enforcement.** The wall budget is enforced by a QuickJS interrupt handler that fires between bytecode ops; while an embedding or `ctx.fetch` request is in flight the engine never regains control, so the deadline is noticed only once the call returns. Bounding a host call therefore means handing the HTTP client timeouts that already fit the remaining budget - which is what `resolveEmbedBudget()` (`functions/embed_budget.hpp`, pure) does. It exists because a 10 s-budget run took **14314 ms**: the READ timeout was clamped to the budget and the CONNECT timeout was not, and the two are additive, so a connect stall burned the full `embedding_connect_timeout_sec` outside the budget. Connect gets at most HALF the available time (a reachable provider connects in well under a second, and a large connect allowance only starves the read phase). Below a 2 s budget the 1 s floor on each phase dominates and the worst case is 2 s - bounded, and stated rather than glossed over.
 - **A blocking host call cannot be interrupted, so host timeouts ARE the enforcement.** The wall budget is enforced by a QuickJS interrupt handler that fires between bytecode ops; while an embedding or `ctx.fetch` request is in flight the engine never regains control, so the deadline is noticed only once the call returns. Bounding a host call therefore means handing the HTTP client timeouts that already fit the remaining budget - which is what `resolveEmbedBudget()` (`functions/embed_budget.hpp`, pure) does. It exists because a 10 s-budget run took **14314 ms**: the READ timeout was clamped to the budget and the CONNECT timeout was not, and the two are additive, so a connect stall burned the full `embedding_connect_timeout_sec` outside the budget. Connect gets at most HALF the available time (a reachable provider connects in well under a second, and a large connect allowance only starves the read phase). Below a 2 s budget the 1 s floor on each phase dominates and the worst case is 2 s - bounded, and stated rather than glossed over.
 - **Embedding timeouts are per-project and NARROWING ONLY**, resolved by the same `resolveEmbedding()` that picks the endpoint, so a project's override applies identically to a function and to an HTTP vector route. The effective value is `min(project, global)`: these govern a shared provider connection and a pooled runtime waiting on it, so an override that could RAISE them would let one tenant hold both longer than the operator allowed. A stored value above the global is kept rather than refused - it becomes effective if the global is later lowered. A zero override is "unset", never "no timeout", because 0 means no timeout to the HTTP client and that is precisely the unbounded call the split prevents.
 - **Embedding timeouts are per-project and NARROWING ONLY**, resolved by the same `resolveEmbedding()` that picks the endpoint, so a project's override applies identically to a function and to an HTTP vector route. The effective value is `min(project, global)`: these govern a shared provider connection and a pooled runtime waiting on it, so an override that could RAISE them would let one tenant hold both longer than the operator allowed. A stored value above the global is kept rather than refused - it becomes effective if the global is later lowered. A zero override is "unset", never "no timeout", because 0 means no timeout to the HTTP client and that is precisely the unbounded call the split prevents.
 - **THE FUNCTION SURFACE NEEDED THE SAME FIX, AND NEEDED IT MORE.** `.search()`/`.store()` build their payload in `host_prelude.js` from an EXPLICIT key list, so an unrecognised option is discarded in the prelude **before the host can ever see it** - the host cannot refuse what never arrives, so a host-side check is no protection at all there. That is precisely how `embedTimeoutMs` came to be honoured host-side and never sent by the prelude while a consumer was told a bound was in force. `onlyKnownKeys()` (renamed from `mailOnlyKeys`, since the job is not mail's) now refuses by name in the prelude, and `expectRefused()` asserts the host was never reached rather than only that something threw. A consumer's call sites were ALL on this surface and none on the HTTP route, so fixing only the route would have left the real callers exposed while looking finished.
 - **THE FUNCTION SURFACE NEEDED THE SAME FIX, AND NEEDED IT MORE.** `.search()`/`.store()` build their payload in `host_prelude.js` from an EXPLICIT key list, so an unrecognised option is discarded in the prelude **before the host can ever see it** - the host cannot refuse what never arrives, so a host-side check is no protection at all there. That is precisely how `embedTimeoutMs` came to be honoured host-side and never sent by the prelude while a consumer was told a bound was in force. `onlyKnownKeys()` (renamed from `mailOnlyKeys`, since the job is not mail's) now refuses by name in the prelude, and `expectRefused()` asserts the host was never reached rather than only that something threw. A consumer's call sites were ALL on this surface and none on the HTTP route, so fixing only the route would have left the real callers exposed while looking finished.

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.14.0
+0.15.0

+ 10 - 2
api/llms.txt

@@ -123,7 +123,7 @@ Supported ops: `eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in`, `contains`, `exists`,
 - `in` - value is a JSON array, e.g. `colour:in:["red","yellow"]`.
 - `in` - value is a JSON array, e.g. `colour:in:["red","yellow"]`.
 - `contains` - **array membership**, not substring: it matches when the field is an array holding the value. `colour:contains:yellow` does NOT match the string `"yellow"`.
 - `contains` - **array membership**, not substring: it matches when the field is an array holding the value. `colour:contains:yellow` does NOT match the string `"yellow"`.
 - `search` - **IGNORES THE FIELD NAME.** A case-insensitive substring over the WHOLE document: its id, its keys, and every string and number in it. So `colour:search:ell` matches `"yellow"` in `colour` AND a document whose `note` says "excellent", AND one whose id contains `ell`. The field is syntactically required and semantically discarded - `nosuchfield:search:ell` matches exactly what `colour:search:ell` does. **For a substring within ONE field, use `regex` on that field.** Worth care if a `search` filter is doing scoping work: it admits rows you may believe it excludes, and in the same direction as a filter that was dropped entirely.
 - `search` - **IGNORES THE FIELD NAME.** A case-insensitive substring over the WHOLE document: its id, its keys, and every string and number in it. So `colour:search:ell` matches `"yellow"` in `colour` AND a document whose `note` says "excellent", AND one whose id contains `ell`. The field is syntactically required and semantically discarded - `nosuchfield:search:ell` matches exactly what `colour:search:ell` does. **For a substring within ONE field, use `regex` on that field.** Worth care if a `search` filter is doing scoping work: it admits rows you may believe it excludes, and in the same direction as a filter that was dropped entirely.
-- `regex` - regular-expression match, and the field IS honoured. This is the field-scoped substring: `colour:regex:ell`. **Three things about it are measurable and none of them announce themselves, so read this before building a search box on it.** Everything in the four bullets below was measured against **database 2.17.2**, which is what the deployed server runs today. **A move to RE2 is in progress upstream and will change three of the four**, so treat these as the behaviour of the current server rather than as a standing contract: under RE2 a character class becomes character-oriented (so `[áÁ]` starts working), `(?i)` becomes valid, an invalid pattern becomes a real error instead of an empty result, and the exponential backtracking goes away - while **backreferences and lookaround stop being supported**, since RE2 has neither. **The one piece of advice that is correct under BOTH engines is to spell alternatives out as alternation** (`sz(?:á|Á)mfejt`) and to escape anything a user typed; a pattern written that way needs no change when the server moves. This paragraph will be updated when it ships.
+- `regex` - regular-expression match, and the field IS honoured. This is the field-scoped substring: `colour:regex:ell`. **Three things about it are measurable and none of them announce themselves, so read this before building a search box on it.** **Which behaviour you get depends on the DATABASE version, and the two are very different.** **From database 2.20.0 the engine is RE2**: linear time, UTF-8 aware, and an invalid pattern is a real error (our 422 `invalid_pattern`, where the reason reaches you only through a 2.17.0-or-newer client - until then it arrives as the bare `validation` slug). `(?i)` works, non-ASCII included, and a character class is character-oriented, so `sz[áÁ]mfejt` matches `számfejt` and `[öÖ]` matches only text actually containing `ö` or `Ö`. **The one thing RE2 takes away: backreferences and lookaround are refused as `invalid_pattern`**, since RE2 has neither - that is the only direction in which a working query stops working. **Below 2.20.0** - which includes the currently deployed server, so this is what you will observe today - the four bullets below apply instead; they were measured against **2.17.2**. A server reports `re2_regex_filters` in its capabilities exactly when it has the new engine, so that, not a version string, is the thing to branch on if you must. **The advice that is correct under BOTH engines is to spell alternatives out as alternation** (`sz(?:á|Á)mfejt`) and to escape anything a user typed; a pattern written that way needs no change when the server moves, and avoiding nested quantifiers costs nothing on RE2.
   - **Matching is CASE-SENSITIVE and there is no flag to ask otherwise.** `text:regex:dolgoz` and `text:regex:Dolgoz` are different queries. **`(?i)` does NOT work** - it is not valid in this grammar, and an invalid pattern behaves as described two bullets down, so `(?i)Dolgoz` reads as "no matches" rather than as an error. Case-fold caller-side: spell the alternatives out, e.g. `text:regex:(?:d|D)olgoz`.
   - **Matching is CASE-SENSITIVE and there is no flag to ask otherwise.** `text:regex:dolgoz` and `text:regex:Dolgoz` are different queries. **`(?i)` does NOT work** - it is not valid in this grammar, and an invalid pattern behaves as described two bullets down, so `(?i)Dolgoz` reads as "no matches" rather than as an error. Case-fold caller-side: spell the alternatives out, e.g. `text:regex:(?:d|D)olgoz`.
   - **The engine is BYTE-oriented, not UTF-8 aware, so a CHARACTER CLASS over non-ASCII text is wrong in BOTH directions.** A character class matches one BYTE, and any non-ASCII character is several. So `sz[áÁ]mfejt` can never match `számfejt` - it reads as "no matches" - while `[öÖ]` matches almost every Hungarian sentence, because `ö` and `Ö` share the lead byte `0xC3` with `á é í ó ú ü ő ű` and the class degenerates into match-nearly-anything. One failure reads as an empty corpus and the other as a broken search; neither reports a fault. **Use ALTERNATION of the whole sequences instead of a class**: `sz(?:á|Á)mfejt` is correct and was measured correct. The same caution applies to `.`, `\w` and any quantifier applied to a non-ASCII character, since each addresses bytes rather than characters.
   - **The engine is BYTE-oriented, not UTF-8 aware, so a CHARACTER CLASS over non-ASCII text is wrong in BOTH directions.** A character class matches one BYTE, and any non-ASCII character is several. So `sz[áÁ]mfejt` can never match `számfejt` - it reads as "no matches" - while `[öÖ]` matches almost every Hungarian sentence, because `ö` and `Ö` share the lead byte `0xC3` with `á é í ó ú ü ő ű` and the class degenerates into match-nearly-anything. One failure reads as an empty corpus and the other as a broken search; neither reports a fault. **Use ALTERNATION of the whole sequences instead of a class**: `sz(?:á|Á)mfejt` is correct and was measured correct. The same caution applies to `.`, `\w` and any quantifier applied to a non-ASCII character, since each addresses bytes rather than characters.
   - **AN INVALID PATTERN MATCHES NOTHING AND ANSWERS 200 - it is NOT an error.** `text:regex:dolgoz(` cannot compile, and the response is a clean empty result list, indistinguishable from a valid pattern that genuinely matched no rows. Note this is a different layer from the **400** `bad_filter` below, which catches a malformed `field:op:value` SPEC: a well-formed spec carrying a broken PATTERN is not currently refused anywhere. **So never pass end-user text through to `regex` unescaped** - every unbalanced `(`, `[` or trailing `\` a customer types in a search box will look to them like an empty knowledge base. Escape the input, or validate the pattern before sending it.
   - **AN INVALID PATTERN MATCHES NOTHING AND ANSWERS 200 - it is NOT an error.** `text:regex:dolgoz(` cannot compile, and the response is a clean empty result list, indistinguishable from a valid pattern that genuinely matched no rows. Note this is a different layer from the **400** `bad_filter` below, which catches a malformed `field:op:value` SPEC: a well-formed spec carrying a broken PATTERN is not currently refused anywhere. **So never pass end-user text through to `regex` unescaped** - every unbalanced `(`, `[` or trailing `\` a customer types in a search box will look to them like an empty knowledge base. Escape the input, or validate the pattern before sending it.
@@ -280,10 +280,18 @@ export default async function (ctx) {
 }
 }
 ```
 ```
 
 
-`on` fields: `id` (required), `type` (`http`, default), `route` (required for http), `method` (a string or an array of strings; **absent means every method**), `auth` (`public` default, or `key` to require an API key - http only, see "Calling a function"), `timeoutMs` (clamped to the runner's ceiling), `singleFlight`. The STORED `descriptor` always reports `method` as an **array**, and omits it entirely when the function accepts any method - a client rendering it must not assume the singular form the source uses.
+`on` fields: `id` (required), `type` (`http`, default), `route` (required for http), `method` (a string or an array of strings; **absent means every method**), `auth` (`public` default, or `key` to require an API key - http only, see "Calling a function"), `watch` (error only, see below), `timeoutMs` (clamped to the runner's ceiling), `singleFlight`. The STORED `descriptor` always reports `method` as an **array**, and omits it entirely when the function accepts any method - a client rendering it must not assume the singular form the source uses.
 
 
 `ctx` carries the trigger: `method`, `path`, `params` (the `:name` captures), `query`, `headers`, `body`. Repeated query keys collapse to the last value.
 `ctx` carries the trigger: `method`, `path`, `params` (the `:name` captures), `query`, `headers`, `body`. Repeated query keys collapse to the last value.
 
 
+**`type: 'error'` runs a function when ANOTHER function fails** (0.15.0+). Like `job` it declares no route and no schedule and **cannot be called directly** - there is no public endpoint, so nobody can fake an alert. `watch` names the function whose failures it answers and defaults to `*`, every function in the project.
+- It receives `ctx.body.failure` carrying `function_id`, `run_id`, `trigger`, `status`, `error`, `started_at` and `duration_ms`, plus `failure_kind` when the failure was classified (`function_fault`, `runner_fault`, `transient_lookup`, `malformed`). **`failure_kind` is ABSENT rather than empty when nobody classified it** - an HTTP run has no queue to classify it - so a handler can tell "not classified" from a classification it does not recognise. Everything is nested under `failure` so a handler can tell this payload from a cron or db one without guessing.
+- **The failing function's error text IS given to the handler**, unlike the caller of the failed function, who never sees it. A handler is server-side code written by the same tenant, which is the whole reason to have one.
+- **It is ENQUEUED, not run inline**, so it needs the job queue and the runner's `jobs.enabled`. A failing request never waits on the handler that reports it, and a slow handler cannot hold the socket of a request that already went wrong. Delivery is at-least-once like any job, **so a handler must be idempotent** - it may run twice for one failure.
+- **`watch` is matched EXACTLY; there is no globbing beyond the bare `*`.** A prefix match would quietly start catching functions added later, and a handler silently widening its own scope is the opposite of what you want from one.
+- **A FAILING ERROR HANDLER TRIGGERS NOTHING - not itself, and not another error handler.** This is a hard rule, not a depth limit: there is no legitimate reason to report the failure of a failure reporter, and the shape being prevented is a handler that tries to e-mail an alert, fails because egress is denied, and triggers itself forever on your own queue. Two handlers both watching `*` would otherwise ping-pong indefinitely. So **an error handler's own failures are visible only in the run log**, which is where to look when alerts stop arriving.
+- A disabled or invalid handler is not a handler, and with no job queue configured a failure dispatches nothing - deliberately silent, since a deployment with no queue has nothing to drain one either.
+
 - **A project can be denied the network entirely.** `PUT /api/v1/projects/{p}/settings/functions` with `{"network_egress":"deny"}` (admin only) stops **both** `ctx.fetch` and `ctx.mail` for that project, refused as `egress_blocked` **before any name is resolved** - so a denied project emits no DNS query either. `"allow"` restores it, `null` inherits. The GET returns the effective value plus `network_egress_set`, which says whether it was chosen for the project or inherited. The default is **allow**, for compatibility rather than preference: `ctx.fetch` shipped with no gate, so defaulting to deny would have stopped every already-deployed function that makes an outbound call. One setting covers both surfaces on purpose - gating one and not the other would let an operator believe a tenant was offline while the other stayed open.
 - **A project can be denied the network entirely.** `PUT /api/v1/projects/{p}/settings/functions` with `{"network_egress":"deny"}` (admin only) stops **both** `ctx.fetch` and `ctx.mail` for that project, refused as `egress_blocked` **before any name is resolved** - so a denied project emits no DNS query either. `"allow"` restores it, `null` inherits. The GET returns the effective value plus `network_egress_set`, which says whether it was chosen for the project or inherited. The default is **allow**, for compatibility rather than preference: `ctx.fetch` shipped with no gate, so defaulting to deny would have stopped every already-deployed function that makes an outbound call. One setting covers both surfaces on purpose - gating one and not the other would let an operator believe a tenant was offline while the other stayed open.
 - **A BINARY request body arrives as base64, not in `ctx.body`.** When the bytes are not valid UTF-8 - an image, a PDF, a protobuf - `ctx.body` is **`null`**, `ctx.bodyBase64` carries the bytes and `ctx.bodyEncoding` is `"base64"`. They go under their own keys rather than into `ctx.body` on purpose: base64 in `ctx.body` would hand a function that knows nothing of binary a plausible-looking string that is not the body that was sent, and silent corruption is worse than an obvious `null`. `ctx.bodyEncoding` is **absent** for a text body, so a function written before this behaves exactly as it did. Note the bytes decide and the content type does not: a body declared `application/json` that cannot be a JSON string is still offered as base64.
 - **A BINARY request body arrives as base64, not in `ctx.body`.** When the bytes are not valid UTF-8 - an image, a PDF, a protobuf - `ctx.body` is **`null`**, `ctx.bodyBase64` carries the bytes and `ctx.bodyEncoding` is `"base64"`. They go under their own keys rather than into `ctx.body` on purpose: base64 in `ctx.body` would hand a function that knows nothing of binary a plausible-looking string that is not the body that was sent, and silent corruption is worse than an obvious `null`. `ctx.bodyEncoding` is **absent** for a text body, so a function written before this behaves exactly as it did. Note the bytes decide and the content type does not: a body declared `application/json` that cannot be a JSON string is still offered as base64.
 
 

+ 1 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "openapi": "3.1.0",
   "info": {
   "info": {
     "title": "smartbotic-vectorapi",
     "title": "smartbotic-vectorapi",
-    "version": "0.14.0",
+    "version": "0.15.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   },
   "components": {
   "components": {

+ 2 - 0
src/CMakeLists.txt

@@ -54,6 +54,8 @@ add_library(vectorapi_core STATIC
     functions/timezone.cpp
     functions/timezone.cpp
     functions/descriptor.cpp
     functions/descriptor.cpp
     functions/fn_gate.cpp
     functions/fn_gate.cpp
+    functions/error_hook.cpp
+    function_error_dispatch.cpp
     functions/net_guard.cpp
     functions/net_guard.cpp
 )
 )
 target_include_directories(vectorapi_core PUBLIC
 target_include_directories(vectorapi_core PUBLIC

+ 61 - 0
src/function_error_dispatch.cpp

@@ -0,0 +1,61 @@
+#include "function_error_dispatch.hpp"
+#include "function_record.hpp"
+#include <spdlog/spdlog.h>
+
+namespace svapi {
+
+void dispatchErrorHandlers(ServerDeps& d, const std::string& project,
+                           const FunctionRunLog& entry, functions::TriggerType failedType) {
+    if (entry.ok) return;
+    if (!d.jobs) return;  // nothing would ever drain it; see ServerDeps::jobs
+
+    functions::FailedRun failed;
+    failed.functionId = entry.functionId;
+    failed.type = failedType;
+    failed.runId = entry.runId;
+    failed.trigger = entry.trigger;
+    failed.status = entry.status;
+    failed.failureKind = entry.failureKind;
+    failed.error = entry.error;
+    failed.startedAt = entry.startedAt;
+    failed.durationMs = entry.durationMs;
+
+    // The loop guard is cheap and the registry read is not, so ask the pure
+    // function first: an error handler that failed must not cause a registry
+    // listing on every one of its own failures.
+    if (failed.type == functions::TriggerType::Error) return;
+
+    try {
+        std::vector<functions::ErrorHandlerCandidate> candidates;
+        for (const FunctionRecord& row : d.functions.list(project)) {
+            // A disabled or invalid handler is not a handler. Same rule as
+            // dispatch: an operator who turned one off meant it.
+            if (!row.enabled || !row.valid) continue;
+            functions::ParseResult parsed = functions::parseDescriptor(row.descriptor);
+            if (!parsed.ok || parsed.descriptor.type != functions::TriggerType::Error) continue;
+            candidates.push_back({row.functionId, std::move(parsed.descriptor)});
+        }
+        if (candidates.empty()) return;
+
+        const nlohmann::json payload = functions::errorHookPayload(failed);
+        for (const std::string& handler : functions::selectErrorHandlers(failed, candidates)) {
+            FunctionJob job;
+            job.project = project;
+            job.functionId = handler;
+            job.trigger = "error";
+            job.payload = payload;
+            // depth stays 0: the loop guard is categorical rather than a
+            // budget, so there is no chain to count. Carried as a field only
+            // because every queue row has one.
+            d.jobs->enqueue(job);
+        }
+    } catch (const std::exception& e) {
+        // Best-effort by design. The function's own failure is the fact the
+        // caller is reporting, and losing the alert must not turn it into a
+        // different, more confusing failure.
+        spdlog::warn("could not dispatch error handlers for {}/{} run {}: {}", project,
+                     entry.functionId, entry.runId, e.what());
+    }
+}
+
+} // namespace svapi

+ 29 - 0
src/function_error_dispatch.hpp

@@ -0,0 +1,29 @@
+#pragma once
+#include "function_run_log.hpp"
+#include "functions/error_hook.hpp"
+#include "server.hpp"
+#include <string>
+
+namespace svapi {
+
+/// Enqueue the project's error handlers for a run that failed.
+///
+/// ONE implementation, called from every place that records a failed run.
+/// There are two such places today (`/fn` dispatch and the invoke route) and
+/// the temptation is to inline four lines at each - which is exactly how this
+/// codebase ended up with `unknownKeys()` called in a single handler while six
+/// siblings stayed broken. A new producer of failed runs should call this
+/// rather than grow a third copy.
+///
+/// Never throws and never changes the answer the caller is about to send: a
+/// failing function that ALSO could not enqueue its handler must still report
+/// its own failure, exactly as recordRun already treats a log append as
+/// best-effort. A refusal to enqueue is logged and dropped.
+///
+/// Does nothing at all when the run succeeded, when the failed function is
+/// itself an error handler (the loop guard, in selectErrorHandlers), or when
+/// this deployment has no job queue.
+void dispatchErrorHandlers(ServerDeps& d, const std::string& project,
+                           const FunctionRunLog& entry, functions::TriggerType failedType);
+
+} // namespace svapi

+ 21 - 1
src/functions/descriptor.cpp

@@ -141,6 +141,10 @@ nlohmann::json FunctionDescriptor::toJson() const {
     case TriggerType::Job:
     case TriggerType::Job:
         j["type"] = "job";
         j["type"] = "job";
         break;
         break;
+    case TriggerType::Error:
+        j["type"] = "error";
+        j["watch"] = watch;
+        break;
     case TriggerType::Db:
     case TriggerType::Db:
         j["type"] = "db";
         j["type"] = "db";
         j["table"] = table;
         j["table"] = table;
@@ -179,8 +183,10 @@ ParseResult parseDescriptor(const nlohmann::json& on) {
             d.type = TriggerType::Db;
             d.type = TriggerType::Db;
         } else if (t == "job") {
         } else if (t == "job") {
             d.type = TriggerType::Job;
             d.type = TriggerType::Job;
+        } else if (t == "error") {
+            d.type = TriggerType::Error;
         } else {
         } else {
-            return fail("'type' must be one of http, cron, db, job: '" + t + "'");
+            return fail("'type' must be one of http, cron, db, job, error: '" + t + "'");
         }
         }
     }
     }
 
 
@@ -226,6 +232,20 @@ ParseResult parseDescriptor(const nlohmann::json& on) {
         // Nothing required. A job function is reached only by being enqueued,
         // Nothing required. A job function is reached only by being enqueued,
         // so it declares no route and no schedule - that is the whole point.
         // so it declares no route and no schedule - that is the whole point.
         break;
         break;
+    case TriggerType::Error: {
+        // `watch` is optional and defaults to every function in the project.
+        if (on.contains("watch")) {
+            if (!on.at("watch").is_string()) return fail("error 'watch' must be a string");
+            d.watch = trim(on.at("watch").get<std::string>());
+            // Refused rather than silently treated as `*`: an empty watch is
+            // almost certainly a template that did not get substituted, and
+            // reading it as "everything" would wire up a handler the author
+            // never asked for.
+            if (d.watch.empty())
+                return fail("error 'watch' must not be empty: use '*' to watch every function");
+        }
+        break;
+    }
     case TriggerType::Db: {
     case TriggerType::Db: {
         if (!on.contains("table")) return fail("db 'table' is required");
         if (!on.contains("table")) return fail("db 'table' is required");
         if (!on.at("table").is_string()) return fail("db 'table' must be a string");
         if (!on.at("table").is_string()) return fail("db 'table' must be a string");

+ 16 - 1
src/functions/descriptor.hpp

@@ -13,7 +13,12 @@ namespace svapi::functions {
 /// enqueue route, or a delayed call-back. It has no route and no schedule, so
 /// enqueue route, or a delayed call-back. It has no route and no schedule, so
 /// it cannot be reached by accident, which is what makes it the right home for
 /// it cannot be reached by accident, which is what makes it the right home for
 /// slow work: a webhook answers fast and hands the real job to one of these.
 /// slow work: a webhook answers fast and hands the real job to one of these.
-enum class TriggerType { Http, Cron, Db, Job };
+/// Error: runs when ANOTHER function fails. Reached only by a failure, so
+/// like Job it declares no route and no schedule and cannot be called
+/// directly. It is enqueued rather than run inline, because a failing request
+/// must not wait on the handler that reports it, and a slow handler must not
+/// hold the socket of the request that already went wrong.
+enum class TriggerType { Http, Cron, Db, Job, Error };
 
 
 enum class DbEvent { Insert, Update, Delete };
 enum class DbEvent { Insert, Update, Delete };
 
 
@@ -95,6 +100,16 @@ struct FunctionDescriptor {
     std::string table;
     std::string table;
     DbEvent event = DbEvent::Insert;
     DbEvent event = DbEvent::Insert;
 
 
+    // Error
+    /// Which function's failures this handler watches. `*` (the default) means
+    /// every function in the project EXCEPT other error handlers.
+    ///
+    /// A literal function id otherwise; no globbing beyond the bare `*`,
+    /// because a prefix match over function ids would quietly start catching
+    /// functions added later, and an error handler silently widening its own
+    /// scope is the opposite of what an operator wants from one.
+    std::string watch = "*";
+
     // Common
     // Common
     /// Per-script wall-clock budget. 0 means "not declared", and the runner
     /// Per-script wall-clock budget. 0 means "not declared", and the runner
     /// applies its default.
     /// applies its default.

+ 43 - 0
src/functions/error_hook.cpp

@@ -0,0 +1,43 @@
+#include "functions/error_hook.hpp"
+
+namespace svapi::functions {
+
+std::vector<std::string> selectErrorHandlers(
+    const FailedRun& failed, const std::vector<ErrorHandlerCandidate>& candidates) {
+    std::vector<std::string> out;
+
+    // THE LOOP GUARD. An error handler's own failure reports to nobody; see
+    // the header for why this is a hard rule and not a depth budget.
+    if (failed.type == TriggerType::Error) return out;
+
+    for (const ErrorHandlerCandidate& c : candidates) {
+        if (c.descriptor.type != TriggerType::Error) continue;
+        // Defence in depth: even with the guard above, a handler must never be
+        // selected for its own failure. Cheap, and it means the two
+        // conditions cannot both be edited away at once.
+        if (c.functionId == failed.functionId) continue;
+        if (c.descriptor.watch == "*" || c.descriptor.watch == failed.functionId)
+            out.push_back(c.functionId);
+    }
+    return out;
+}
+
+nlohmann::json errorHookPayload(const FailedRun& failed) {
+    nlohmann::json failure{
+        {"function_id", failed.functionId},
+        {"run_id", failed.runId},
+        {"trigger", failed.trigger},
+        {"status", failed.status},
+        {"error", failed.error},
+        {"started_at", failed.startedAt},
+        {"duration_ms", failed.durationMs},
+    };
+    // Written only when the producer classified it, so a handler can tell "not
+    // classified" from a classification it does not recognise. An HTTP run has
+    // no queue to classify it, so this is legitimately absent rather than
+    // unknown.
+    if (!failed.failureKind.empty()) failure["failure_kind"] = failed.failureKind;
+    return nlohmann::json{{"failure", std::move(failure)}};
+}
+
+} // namespace svapi::functions

+ 73 - 0
src/functions/error_hook.hpp

@@ -0,0 +1,73 @@
+#pragma once
+#include "functions/descriptor.hpp"
+#include <nlohmann/json.hpp>
+#include <string>
+#include <vector>
+
+namespace svapi::functions {
+
+/// Choosing and feeding the error handlers that answer a failed run.
+///
+/// Pure on purpose, like `invoke_envelope.hpp` and `wall_budget.hpp`: the two
+/// things that can go badly wrong here - dispatching a handler for a failure
+/// it should not see, and dispatching one in a loop - are decidable from
+/// facts, with no database, no queue and no runner. So they are decided here
+/// and enumerated in tests, rather than inferred from the behaviour of a
+/// handler that only misbehaves in production.
+
+/// What failed. Everything an error handler is told, and nothing more.
+struct FailedRun {
+    /// The function that failed.
+    std::string functionId;
+    /// Its trigger type, which is what the loop guard turns on.
+    TriggerType type = TriggerType::Http;
+    /// The run id, so a handler can fetch the full run log entry.
+    std::string runId;
+    /// "http", "invoke", "cron", "db" - how the failed function was reached.
+    std::string trigger;
+    /// The HTTP status the failure was reported as, 0 when it had none.
+    int status = 0;
+    /// Stable classification when one exists ("function_fault",
+    /// "runner_fault", "transient_lookup", "malformed"), else empty.
+    std::string failureKind;
+    /// The failure message. NOT forwarded to the caller of the failed
+    /// function, but an error handler is server-side code written by the same
+    /// tenant, so it does get it - that is the whole reason to have one.
+    std::string error;
+    uint64_t startedAt = 0;
+    int64_t durationMs = 0;
+};
+
+/// One candidate handler: its id and what it declared.
+struct ErrorHandlerCandidate {
+    std::string functionId;
+    /// Must be a parsed descriptor of type Error; anything else is ignored.
+    FunctionDescriptor descriptor;
+};
+
+/// Which handlers should run for this failure, in the order given.
+///
+/// THE LOOP GUARD IS THE POINT OF THIS FUNCTION, and it is a hard rule rather
+/// than a depth counter: **a failing error handler never triggers an error
+/// handler, including itself.** A depth limit would still permit one wasteful
+/// extra run per failure and, worse, would make an infinite loop a question of
+/// configuration - the `events.max_depth` approach is right for db triggers,
+/// where chaining is legitimate and only runaway chaining is not, but there is
+/// no legitimate reason to report the failure of a failure reporter. The
+/// classic shape this prevents: a handler that tries to e-mail an alert, fails
+/// because egress is denied, and triggers itself forever on a tenant's own
+/// queue.
+///
+/// `watch` is matched exactly, or `*` for every function except other error
+/// handlers. Pure.
+std::vector<std::string> selectErrorHandlers(const FailedRun& failed,
+                                             const std::vector<ErrorHandlerCandidate>& candidates);
+
+/// The `ctx` payload an error handler receives, under a single `failure` key.
+///
+/// Nested rather than spread at the top level so a handler can tell a failure
+/// payload from a cron or db one without guessing, and so adding a field later
+/// cannot collide with a key the trigger shape already uses.
+nlohmann::json errorHookPayload(const FailedRun& failed);
+
+} // namespace svapi::functions

+ 6 - 0
src/handlers/function_dispatch.cpp

@@ -11,6 +11,7 @@
 #include "errors.hpp"
 #include "errors.hpp"
 #include "functions/trigger_body.hpp"
 #include "functions/trigger_body.hpp"
 #include "functions/descriptor.hpp"
 #include "functions/descriptor.hpp"
+#include "function_error_dispatch.hpp"
 #include "functions/fn_gate.hpp"
 #include "functions/fn_gate.hpp"
 #include "rate_limiter.hpp"
 #include "rate_limiter.hpp"
 #include "json_http.hpp"
 #include "json_http.hpp"
@@ -218,6 +219,11 @@ void recordRun(ServerDeps& d, const std::string& project, const FunctionRunLog&
         spdlog::warn("could not record run {} of {}/{}: {}", entry.runId, project,
         spdlog::warn("could not record run {} of {}/{}: {}", entry.runId, project,
                      entry.functionId, e.what());
                      entry.functionId, e.what());
     }
     }
+    // Error handlers hang off the same point as the log, so a failure cannot
+    // be recorded without them being considered. Every function reached
+    // through this route is an Http one by construction - matchHttpRoute skips
+    // anything else - so the failed type is not inferred.
+    dispatchErrorHandlers(d, project, entry, functions::TriggerType::Http);
 }
 }
 
 
 void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res) {
 void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res) {

+ 15 - 0
src/handlers/functions.cpp

@@ -1,4 +1,5 @@
 #include "errors.hpp"
 #include "errors.hpp"
+#include "function_error_dispatch.hpp"
 #include "function_record.hpp"
 #include "function_record.hpp"
 #include "functions/invoke_envelope.hpp"
 #include "functions/invoke_envelope.hpp"
 #include "json_http.hpp"
 #include "json_http.hpp"
@@ -314,6 +315,20 @@ void registerFunctionRoutes(ApiServer& s) {
         // exactly the one an operator goes looking for afterwards.
         // exactly the one an operator goes looking for afterwards.
         d->functionRuns.append(project, entry);
         d->functionRuns.append(project, entry);
 
 
+        // Error handlers, from the same point as the log. Unlike /fn, this
+        // route can invoke a function of ANY trigger type, so the failed
+        // type has to be read from the row rather than assumed - it is what
+        // the loop guard turns on. An unparseable descriptor defaults to
+        // Error, which SUPPRESSES dispatch: failing closed here costs a
+        // missed alert on a function that is invalid anyway, while failing
+        // open risks an error handler triggering itself.
+        {
+            const functions::ParseResult invoked = functions::parseDescriptor(fn->descriptor);
+            dispatchErrorHandlers(*d, project, entry,
+                                  invoked.ok ? invoked.descriptor.type
+                                             : functions::TriggerType::Error);
+        }
+
         if (r.transportFailure)
         if (r.transportFailure)
             throw ApiError(ErrCode::Unavailable, "runner_unreachable",
             throw ApiError(ErrCode::Unavailable, "runner_unreachable",
                            r.error.empty() ? "the function runner could not be reached" : r.error,
                            r.error.empty() ? "the function runner could not be reached" : r.error,

+ 1 - 1
src/main.cpp

@@ -137,7 +137,7 @@ int main(int argc, char** argv) {
 
 
     svapi::ServerDeps deps{db,        settings,     keys,          registry,
     svapi::ServerDeps deps{db,        settings,     keys,          registry,
                            sessions,  functions,    functionRuns,  runners.get(),
                            sessions,  functions,    functionRuns,  runners.get(),
-                           cfg.webuiDir, shareDir};
+                           cfg.webuiDir, shareDir, &jobQueue};
     svapi::ApiServer server(std::move(deps));
     svapi::ApiServer server(std::move(deps));
     if (runners && cfg.schedulerEnabled) {
     if (runners && cfg.schedulerEnabled) {
         svapi::FunctionSchedulerOptions so;
         svapi::FunctionSchedulerOptions so;

+ 9 - 0
src/server.hpp

@@ -4,6 +4,7 @@
 #include "collection_registry.hpp"
 #include "collection_registry.hpp"
 #include "db_gateway.hpp"
 #include "db_gateway.hpp"
 #include "function_registry.hpp"
 #include "function_registry.hpp"
+#include "function_jobs.hpp"
 #include "function_run_log.hpp"
 #include "function_run_log.hpp"
 #include "principal.hpp"
 #include "principal.hpp"
 #include "runner_client.hpp"
 #include "runner_client.hpp"
@@ -28,6 +29,14 @@ struct ServerDeps {
     RunnerPool* runners = nullptr;
     RunnerPool* runners = nullptr;
     std::string webuiDir;   // static SPA root ("" disables)
     std::string webuiDir;   // static SPA root ("" disables)
     std::string shareDir;   // openapi.json + llms.txt dir
     std::string shareDir;   // openapi.json + llms.txt dir
+    /// Null when this deployment has no job queue wired. Error handlers are
+    /// ENQUEUED rather than run inline, so without it a failure simply
+    /// dispatches no handler - deliberately silent, because a deployment with
+    /// no queue has nothing to drain one either.
+    ///
+    /// Last in the struct so every existing positional initialiser still
+    /// compiles and defaults it to null.
+    FunctionJobQueue* jobs = nullptr;
 };
 };
 
 
 class ApiServer {
 class ApiServer {

+ 11 - 0
tests/CMakeLists.txt

@@ -96,6 +96,17 @@ target_link_libraries(test_functions_descriptor PRIVATE
     nlohmann_json::nlohmann_json GTest::gtest_main)
     nlohmann_json::nlohmann_json GTest::gtest_main)
 gtest_discover_tests(test_functions_descriptor)
 gtest_discover_tests(test_functions_descriptor)
 
 
+# The error-handler trigger: selection, the loop guard and the payload.
+add_executable(test_error_hook
+    test_error_hook.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/error_hook.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/descriptor.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/cron.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/timezone.cpp)
+target_include_directories(test_error_hook PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_error_hook PRIVATE nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_error_hook)
+
 # The /fn gate: pure policy decision plus the descriptor's auth mode.
 # The /fn gate: pure policy decision plus the descriptor's auth mode.
 add_executable(test_fn_gate
 add_executable(test_fn_gate
     test_fn_gate.cpp
     test_fn_gate.cpp

+ 185 - 0
tests/test_error_hook.cpp

@@ -0,0 +1,185 @@
+// The error-handler trigger: which handlers answer a failed run, and what
+// they are told.
+//
+// Pure, so the two things that can go badly wrong - dispatching a handler for
+// a failure it should not see, and dispatching in a loop - are enumerated
+// here rather than discovered in production.
+#include "functions/descriptor.hpp"
+#include "functions/error_hook.hpp"
+#include <gtest/gtest.h>
+
+using namespace svapi::functions;
+
+namespace {
+
+ErrorHandlerCandidate handler(const std::string& id, const std::string& watch) {
+    nlohmann::json on{{"id", id}, {"type", "error"}, {"watch", watch}};
+    ParseResult p = parseDescriptor(on);
+    EXPECT_TRUE(p.ok) << p.error;
+    return {id, p.descriptor};
+}
+
+FailedRun httpFailure(const std::string& id) {
+    FailedRun f;
+    f.functionId = id;
+    f.type = TriggerType::Http;
+    f.runId = "run-1";
+    f.trigger = "http";
+    f.status = 500;
+    f.error = "TypeError: x is not a function";
+    return f;
+}
+
+} // namespace
+
+// --- The descriptor -----------------------------------------------------
+
+TEST(ErrorDescriptor, ParsesAndDefaultsToWatchingEverything) {
+    const ParseResult r = parseDescriptor({{"id", "alert"}, {"type", "error"}});
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.descriptor.type, TriggerType::Error);
+    EXPECT_EQ(r.descriptor.watch, "*");
+}
+
+TEST(ErrorDescriptor, NeedsNoRouteOrSchedule) {
+    // Like a job function: reached only by a failure, so it declares neither.
+    EXPECT_TRUE(parseDescriptor({{"id", "alert"}, {"type", "error"}}).ok);
+}
+
+TEST(ErrorDescriptor, RefusesAnEmptyWatchRatherThanTreatingItAsEverything) {
+    // An empty watch is almost always an unsubstituted template, and reading
+    // it as "*" would wire up a handler the author never asked for.
+    const ParseResult r = parseDescriptor({{"id", "a"}, {"type", "error"}, {"watch", ""}});
+    EXPECT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("watch"), std::string::npos);
+}
+
+TEST(ErrorDescriptor, RoundTripsThroughTheStoredRow) {
+    const ParseResult first =
+        parseDescriptor({{"id", "a"}, {"type", "error"}, {"watch", "importer"}});
+    ASSERT_TRUE(first.ok) << first.error;
+    const ParseResult second = parseDescriptor(first.descriptor.toJson());
+    ASSERT_TRUE(second.ok) << second.error;
+    EXPECT_EQ(second.descriptor.type, TriggerType::Error);
+    EXPECT_EQ(second.descriptor.watch, "importer");
+}
+
+TEST(ErrorDescriptor, TheTypeErrorMessageListsEveryValidType) {
+    const ParseResult r = parseDescriptor({{"id", "a"}, {"type", "nonsense"}});
+    EXPECT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("error"), std::string::npos)
+        << "a script author must be able to discover the new type from the error";
+}
+
+// THE PAIRING for the whole trigger type: an error handler must NOT be
+// reachable over HTTP. Without this, declaring one would publish a public
+// endpoint that anyone could call to fake an alert.
+TEST(ErrorDescriptor, AnErrorHandlerIsNotReachableAsAnHttpRoute) {
+    ParseResult p = parseDescriptor({{"id", "alert"}, {"type", "error"}});
+    ASSERT_TRUE(p.ok) << p.error;
+    // Even if the row somehow carried a route, the type is what decides.
+    p.descriptor.route = "/alert";
+    const std::vector<FunctionDescriptor> all{p.descriptor};
+    const RouteMatch m = matchHttpRoute(all, "GET", "/alert");
+    EXPECT_EQ(m.status, RouteMatchStatus::NotFound)
+        << "an error handler must have no public endpoint";
+}
+
+// --- Selection ----------------------------------------------------------
+
+TEST(ErrorHook, AWildcardHandlerAnswersAnyFailure) {
+    const std::vector<std::string> picked =
+        selectErrorHandlers(httpFailure("importer"), {handler("alert", "*")});
+    ASSERT_EQ(picked.size(), 1u);
+    EXPECT_EQ(picked[0], "alert");
+}
+
+TEST(ErrorHook, AHandlerWatchingThatFunctionAnswers) {
+    const std::vector<std::string> picked =
+        selectErrorHandlers(httpFailure("importer"), {handler("alert", "importer")});
+    ASSERT_EQ(picked.size(), 1u);
+}
+
+TEST(ErrorHook, AHandlerWatchingADifferentFunctionDoesNot) {
+    EXPECT_TRUE(
+        selectErrorHandlers(httpFailure("importer"), {handler("alert", "exporter")}).empty());
+}
+
+TEST(ErrorHook, WatchIsMatchedEXACTLYwithNoPrefixGlobbing) {
+    // A prefix match would quietly start catching functions added later, and a
+    // handler silently widening its own scope is the opposite of what an
+    // operator wants from one.
+    EXPECT_TRUE(
+        selectErrorHandlers(httpFailure("importer-v2"), {handler("alert", "importer")}).empty());
+    EXPECT_TRUE(
+        selectErrorHandlers(httpFailure("importer"), {handler("alert", "import*")}).empty());
+}
+
+TEST(ErrorHook, NonErrorCandidatesAreIgnored) {
+    ParseResult http = parseDescriptor({{"id", "web"}, {"type", "http"}, {"route", "/w"}});
+    ASSERT_TRUE(http.ok) << http.error;
+    EXPECT_TRUE(selectErrorHandlers(httpFailure("importer"), {{"web", http.descriptor}}).empty());
+}
+
+TEST(ErrorHook, SeveralHandlersAllAnswerInTheOrderGiven) {
+    const std::vector<std::string> picked = selectErrorHandlers(
+        httpFailure("importer"),
+        {handler("page-oncall", "*"), handler("ignore-me", "other"), handler("log-it", "importer")});
+    ASSERT_EQ(picked.size(), 2u);
+    EXPECT_EQ(picked[0], "page-oncall");
+    EXPECT_EQ(picked[1], "log-it");
+}
+
+// --- The loop guard, which is the point ---------------------------------
+
+TEST(ErrorHookLoopGuard, AFailingErrorHandlerTriggersNOTHING) {
+    // The classic shape this prevents: a handler that tries to e-mail an
+    // alert, fails because egress is denied, and triggers itself forever on
+    // the tenant's own queue. A depth budget would still allow one wasteful
+    // run per failure and make an infinite loop a question of configuration.
+    FailedRun failed = httpFailure("alert");
+    failed.type = TriggerType::Error;
+    EXPECT_TRUE(selectErrorHandlers(failed, {handler("alert", "*")}).empty());
+    EXPECT_TRUE(selectErrorHandlers(failed, {handler("other-alert", "*")}).empty())
+        << "not even a DIFFERENT handler may answer a handler's failure - two "
+           "handlers watching * would otherwise ping-pong forever";
+}
+
+TEST(ErrorHookLoopGuard, AHandlerIsNeverSelectedForItsOwnFailure) {
+    // Defence in depth. The type guard above already covers this, and both
+    // conditions exist so they cannot be edited away at once.
+    FailedRun failed = httpFailure("alert");  // deliberately typed Http
+    EXPECT_TRUE(selectErrorHandlers(failed, {handler("alert", "*")}).empty());
+}
+
+// --- The payload --------------------------------------------------------
+
+TEST(ErrorHookPayload, NestsEverythingUnderFailure) {
+    // Nested so a handler can tell a failure payload from a cron or db one
+    // without guessing, and so a field added later cannot collide with a key
+    // the trigger shape already uses.
+    const nlohmann::json p = errorHookPayload(httpFailure("importer"));
+    ASSERT_TRUE(p.contains("failure"));
+    EXPECT_EQ(p["failure"]["function_id"], "importer");
+    EXPECT_EQ(p["failure"]["run_id"], "run-1");
+    EXPECT_EQ(p["failure"]["status"], 500);
+    EXPECT_EQ(p["failure"]["trigger"], "http");
+    EXPECT_NE(p["failure"]["error"].get<std::string>().find("TypeError"), std::string::npos)
+        << "the handler is the tenant's own server-side code and does get the message";
+}
+
+TEST(ErrorHookPayload, OmitsFailureKindWhenNobodyClassifiedIt) {
+    // Absent rather than empty, so a handler can tell "not classified" from a
+    // classification it does not recognise. An HTTP run has no queue to
+    // classify it, so this is legitimately absent rather than unknown.
+    const nlohmann::json p = errorHookPayload(httpFailure("importer"));
+    EXPECT_FALSE(p["failure"].contains("failure_kind"));
+}
+
+TEST(ErrorHookPayload, CarriesFailureKindWhenThereIsOne) {
+    FailedRun f = httpFailure("nightly");
+    f.failureKind = "runner_fault";
+    const nlohmann::json p = errorHookPayload(f);
+    ASSERT_TRUE(p["failure"].contains("failure_kind"));
+    EXPECT_EQ(p["failure"]["failure_kind"], "runner_fault");
+}