Răsfoiți Sursa

feat: persist WHY a job failed, not just that it did

The worker always classified a failure into FunctionFault / RunnerFault /
TransientLookup / Malformed and then threw the classification away:
complete() stored a state and a free-text message, so a failed job recorded
only that it failed and a string nobody could branch on without the
message-text matching this codebase forbids elsewhere.

The kind now reaches the queue row (last_failure_kind) AND the run log
(failure_kind), because the queue row is deleted when a job is reaped while
the run log is what an operator reads - storing it only on the queue would
keep the classification exactly as long as nobody needed it.

It travels as a stable NAME, never the enum's ordinal: inserting a kind
renumbers every one after it and a row written last week would start
reading as a different failure. jobFailureName() is append-only and total -
an unrecognised value answers "unknown" rather than asserting, so a kind
added later is recorded honestly by an older reader.

Two kinds the runner's enum does not have, set by the queue itself:
`abandoned` (a runner died holding the claim and the attempt budget is
spent) and `reclaimed` (a stale claim went back to pending, so the job has
not failed). The runner that would have classified an abandoned job is the
thing that died.

isFunctionAtFault() exists because that is the question actually asked: a
runner_fault is ours and a function_fault is the tenant's, and routing both
to one alarm is how an on-call rota learns to ignore it. The web UI colours
them differently for the same reason, and shows an unrecognised kind
verbatim rather than hiding it.

Prerequisite for #75. 1273/1273 green; both API docs updated.
fszontagh 1 lună în urmă
părinte
comite
078cf86f05

+ 5 - 1
api/llms.txt

@@ -347,7 +347,11 @@ export default async function (ctx) {
 - `PUT  /api/v1/projects/{project}/functions/{id}/policy` `{policy:{rules, origins?, rate_limit_per_min?, expires_at?}}` **(admin)** - Replace what the function may touch. Same vocabulary as a key scope (`rules` of `{collection, ops}` over `read`/`list`/`search`/`insert`/`update`/`delete`), with one difference: an **empty** rule set is legal and means the function reaches nothing. This is the only route that changes a policy.
 - `PUT  /api/v1/projects/{project}/functions/{id}/enabled` `{enabled}` - Enable or disable a function.
 - `POST /api/v1/projects/{project}/functions/{id}/invoke` `{method?, path?, params?, query?, headers?, body?}` - Run the function once and record the run. Every field is optional: an empty body invokes it with its declared route as the path and `POST` as the method. Returns **200** whenever the run was *performed*, with `{run_id, ok, status, headers, body, console, duration_ms, error, timed_out, out_of_memory}` - the function's own failure is in that envelope, not in the HTTP status, so "the function returned 500" stays distinguishable from "the invoke could not be performed". A disabled or invalid function is **409**; a runner that cannot be reached is **503** `runner_unreachable`, and the failed attempt is still logged.
-- `GET  /api/v1/projects/{project}/functions/{id}/logs` - Recorded runs, newest first: `{function_id, runs:[{run_id, function_id, trigger, ok, status, duration_ms, error, console, headers, started_at}]}`. `headers` is omitted when the function set none, and is present so a stored run renders with the same shape as a fresh invoke envelope. `?limit=` defaults to 50. **The log keeps only the newest N runs per function** (trimmed on every write, since there is no scheduler yet), so a limit above N returns N and an old `run_id` eventually stops resolving.
+- `GET  /api/v1/projects/{project}/functions/{id}/logs` - Recorded runs, newest first: `{function_id, runs:[{run_id, function_id, trigger, ok, status, duration_ms, error, console, headers, started_at}]}`. `headers` is omitted when the function set none, and is present so a stored run renders with the same shape as a fresh invoke envelope. `?limit=` defaults to 50.
+  **A failed run now also carries `failure_kind`, which says WHOSE problem it is.** `function_fault` means the script's own doing (it threw, returned a non-response, blew its memory ceiling, is disabled or will not compile) and is never retried. `runner_fault`, `abandoned` (a runner died holding the job) and `malformed` (a corrupt queue row) are OURS, not yours. `transient_lookup` is a registry read that did not answer; `reclaimed` is a stale claim going back for another attempt, so the job has not failed. The classification was always computed and then discarded, so a failed job recorded only a free-text message - and matching on message text is exactly what nobody should have to do.
+  **The field is ABSENT on a successful run AND on a server older than this release, so never read its absence as "no failure" - `ok` is the field that answers that.** The names are append-only and will not be respelled; an unrecognised one is a kind added by a newer server, so treat an unknown value as "something failed, cause not known to me" rather than ignoring the run.
+  `?limit=` is the ONLY parameter: there is no `status` filter, and asking for one is refused 422 rather than silently returning the newest runs of every outcome.
+  **The log keeps only the newest N runs per function** (trimmed on every write, since there is no scheduler yet), so a limit above N returns N and an old `run_id` eventually stops resolving.
 
 ### Calling a function
 

+ 1 - 1
api/openapi.json

@@ -3972,7 +3972,7 @@
       ],
       "get": {
         "summary": "This function's recorded runs, newest first",
-        "description": "The log keeps only the newest N runs per function (trimmed on every write), so a limit above N returns N.\n\n**Refuses a query parameter it cannot honour** (422 `unknown_option`) rather than accepting and ignoring it. Incidental parameters (a cache-buster, `_=<timestamp>`, `utm_*`) are still ignored - what is refused is the set a caller plausibly sends expecting an effect, which is mostly this API's OTHER routes' spellings of the same idea. The error carries `details.unsupported` and, where this route has an equivalent, `details.instead`. Accepted here: `limit`. There is no `status` filter: `status`, `state`, `outcome`, `failed` and `error` are refused, because a request for just the failures would otherwise have returned the newest runs of every outcome.",
+        "description": "The log keeps only the newest N runs per function (trimmed on every write), so a limit above N returns N.\n\n**Refuses a query parameter it cannot honour** (422 `unknown_option`) rather than accepting and ignoring it. Incidental parameters (a cache-buster, `_=<timestamp>`, `utm_*`) are still ignored - what is refused is the set a caller plausibly sends expecting an effect, which is mostly this API's OTHER routes' spellings of the same idea. The error carries `details.unsupported` and, where this route has an equivalent, `details.instead`. Accepted here: `limit`. There is no `status` filter: `status`, `state`, `outcome`, `failed` and `error` are refused, because a request for just the failures would otherwise have returned the newest runs of every outcome.\n\nA failed run carries `failure_kind`, which says whose problem it is: `function_fault` is the script's own doing and is never retried, while `runner_fault`, `abandoned` and `malformed` are the service's. ABSENT on a successful run and on a server older than this release, so `ok` is the field that decides whether a run failed. The names are append-only; treat an unrecognised one as \"failed, cause unknown to me\".",
         "operationId": "listFunctionRuns",
         "parameters": [
           {

+ 3 - 1
runner/src/job_worker.cpp

@@ -260,6 +260,7 @@ JobRunRecord buildRunRecord(const JobView& job, const std::string& runId, uint64
     entry.ok = decision.ok;
     entry.status = decision.status;
     entry.error = decision.error;
+    entry.failureKind = jobFailureName(decision.failure);
     entry.startedAt = startedAt;
     if (runBody.is_object()) {
         if (runBody.contains("duration_ms") && runBody.at("duration_ms").is_number())
@@ -400,7 +401,8 @@ bool JobWorker::runOnce() {
 
     bool completed = false;
     try {
-        completed = queue_.complete(*job, decision.ok, decision.error, decision.retryAfterSec);
+        completed = queue_.complete(*job, decision.ok, decision.error, decision.retryAfterSec,
+                                    jobFailureName(decision.failure));
     } catch (const std::exception& e) {
         spdlog::warn("could not complete job {}: {}", job->jobId, e.what());
     }

+ 41 - 1
runner/src/job_worker.hpp

@@ -82,8 +82,13 @@ public:
     /// Finish a claimed job. `retryAfterSec` > 0 returns it to pending for
     /// another attempt; 0 fails it outright. Which one is decided by
     /// classifyOutcome(), never here.
+    /// `failureKind` is the stable name from `jobFailureName` - stored so a
+    /// failed job records WHY and not merely that it failed. Passed rather
+    /// than re-derived, for the same reason the run kind is a parameter to
+    /// RunService::run: the classification is the caller's knowledge and
+    /// guessing it here would be a second, divergent implementation.
     virtual bool complete(const JobView& job, bool ok, const std::string& error,
-                          uint32_t retryAfterSec) = 0;
+                          uint32_t retryAfterSec, const std::string& failureKind) = 0;
 
     /// Return claims older than `timeoutSec` to pending. Only called when
     /// Options::reclaimIntervalSec is non-zero - see that field.
@@ -101,6 +106,8 @@ struct JobRunRecord {
     int status = 0;
     int64_t durationMs = 0;
     std::string error;
+    /// The stable failure-kind name, from `jobFailureName`. Empty on success.
+    std::string failureKind;
     std::vector<std::string> console;
     nlohmann::json headers = nlohmann::json::object();
     uint64_t startedAt = 0;
@@ -144,6 +151,39 @@ enum class JobFailure {
     Malformed,
 };
 
+/// The STABLE wire name of a failure kind.
+///
+/// A string rather than the enum's ordinal, because the ordinal is not a
+/// contract: inserting a kind renumbers every one after it, and a stored row
+/// written last week would silently start reading as a different failure. The
+/// names are therefore append-only and must never be respelled - the same
+/// discipline as an error slug.
+///
+/// Pure, and deliberately total: an unrecognised value answers "unknown"
+/// rather than asserting, so a kind added later is recorded honestly by an
+/// older reader instead of crashing it.
+inline const char* jobFailureName(JobFailure f) {
+    switch (f) {
+        case JobFailure::None:            return "";
+        case JobFailure::FunctionFault:   return "function_fault";
+        case JobFailure::RunnerFault:     return "runner_fault";
+        case JobFailure::TransientLookup: return "transient_lookup";
+        case JobFailure::Malformed:       return "malformed";
+    }
+    return "unknown";
+}
+
+/// Whether this kind means the FUNCTION is at fault, as opposed to the runner
+/// or the queue row.
+///
+/// The question an error handler and an operator both actually ask, and it is
+/// not derivable from "it failed": a `runner_fault` is our problem and a
+/// `function_fault` is the tenant's, so routing both to the same alarm is how
+/// an on-call rota learns to ignore it.
+inline bool isFunctionAtFault(JobFailure f) {
+    return f == JobFailure::FunctionFault;
+}
+
 /// What to do with a finished run. `retryAfterSec` is what goes to
 /// complete(); 0 means fail outright.
 struct JobDecision {

+ 2 - 2
runner/src/main.cpp

@@ -279,12 +279,12 @@ public:
     }
 
     bool complete(const svapi::runner::JobView& v, bool ok, const std::string& error,
-                  uint32_t retryAfterSec) override {
+                  uint32_t retryAfterSec, const std::string& failureKind) override {
         try {
             svapi::FunctionJob job = svapi::FunctionJob::fromJson(v.raw);
             job.jobId   = v.jobId;                        // the body never carries `id`
             job.version = v.raw.value("version", uint64_t{0});
-            return queue_.complete(job, ok, error, retryAfterSec);
+            return queue_.complete(job, ok, error, retryAfterSec, failureKind);
         } catch (const std::exception& e) {
             spdlog::warn("completing job {} failed: {}", v.jobId, e.what());
             return false;

+ 92 - 2
runner/tests/job_worker_test.cpp

@@ -75,6 +75,10 @@ struct CompletedJob {
     bool ok = false;
     std::string error;
     uint32_t retryAfterSec = 0;
+    /// Recorded so a test can assert the KIND reached the queue. Without this
+    /// the fake would swallow it and every test would pass whether or not the
+    /// classification was passed through at all.
+    std::string failureKind;
 };
 
 class FakeQueue : public JobQueuePort {
@@ -90,9 +94,9 @@ public:
         return job;
     }
     bool complete(const JobView& job, bool ok, const std::string& error,
-                  uint32_t retryAfterSec) override {
+                  uint32_t retryAfterSec, const std::string& failureKind) override {
         std::lock_guard<std::mutex> lock(m);
-        completed.push_back({job.jobId, ok, error, retryAfterSec});
+        completed.push_back({job.jobId, ok, error, retryAfterSec, failureKind});
         return !failComplete;
     }
     uint32_t reclaimStale(uint32_t, uint32_t) override {
@@ -673,3 +677,89 @@ TEST(Threads, TheStaleSweepIsOffUnlessAnIntervalIsSet) {
     }
     EXPECT_GT(queue.sweeps, 0);
 }
+
+// ------------------------------------------------- the failure KIND survives
+
+// The names are a CONTRACT, so they are pinned by value rather than by
+// round-tripping the enum through itself. A test asserting
+// `jobFailureName(FunctionFault) == jobFailureName(FunctionFault)` would pass
+// after someone respelled it, which is precisely the change that must break.
+TEST(FailureKind, TheWireNamesArePinnedByValue) {
+    EXPECT_STREQ("", jobFailureName(JobFailure::None));
+    EXPECT_STREQ("function_fault", jobFailureName(JobFailure::FunctionFault));
+    EXPECT_STREQ("runner_fault", jobFailureName(JobFailure::RunnerFault));
+    EXPECT_STREQ("transient_lookup", jobFailureName(JobFailure::TransientLookup));
+    EXPECT_STREQ("malformed", jobFailureName(JobFailure::Malformed));
+}
+
+// "it failed" is not the question anyone asks. `runner_fault` is ours and
+// `function_fault` is the tenant's, and routing both to one alarm is how an
+// on-call rota learns to ignore it.
+TEST(FailureKind, OnlyAFunctionFaultBlamesTheFunction) {
+    EXPECT_TRUE(isFunctionAtFault(JobFailure::FunctionFault));
+    EXPECT_FALSE(isFunctionAtFault(JobFailure::RunnerFault));
+    EXPECT_FALSE(isFunctionAtFault(JobFailure::TransientLookup));
+    EXPECT_FALSE(isFunctionAtFault(JobFailure::Malformed));
+    EXPECT_FALSE(isFunctionAtFault(JobFailure::None));
+}
+
+// It reaches the QUEUE, which is what #70 was about: the worker always
+// classified the failure and then discarded it, storing only a state and a
+// free-text message.
+TEST(FailureKind, AThrowingFunctionReachesTheQueueAsAFunctionFault) {
+    FakeSource source;
+    source.put("p", "f",
+               "export const on = { id: 'f', type: 'cron', schedule: '* * * * *' };\n"
+               "export default async () => { throw new Error('boom'); };\n");
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    queue.pending.push_back(job("j1", "f"));
+    JobWorker worker(service, queue, log, workerOptions());
+
+    EXPECT_TRUE(worker.runOnce());
+    ASSERT_EQ(queue.completed.size(), 1u);
+    EXPECT_FALSE(queue.completed[0].ok);
+    EXPECT_EQ(queue.completed[0].failureKind, "function_fault");
+    // And onto the run log, which is what an operator reads - the queue row is
+    // deleted when the job is reaped, so storing it only there would keep the
+    // classification exactly as long as nobody needed it.
+    ASSERT_EQ(log.entries.size(), 1u);
+    EXPECT_EQ(log.entries[0].second.failureKind, "function_fault");
+}
+
+// A successful run must carry NO kind. Without this the whole family could be
+// hardcoded to "function_fault" and every test above would still pass.
+TEST(FailureKind, ASuccessfulRunCarriesNoKindAtAll) {
+    FakeSource source;
+    source.put("p", "f",
+               "export const on = { id: 'f', type: 'cron', schedule: '* * * * *' };\n"
+               "export default async () => ({ body: 'ok' });\n");
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    queue.pending.push_back(job("j1", "f"));
+    JobWorker worker(service, queue, log, workerOptions());
+
+    EXPECT_TRUE(worker.runOnce());
+    ASSERT_EQ(queue.completed.size(), 1u);
+    EXPECT_TRUE(queue.completed[0].ok);
+    EXPECT_EQ(queue.completed[0].failureKind, "");
+    ASSERT_EQ(log.entries.size(), 1u);
+    EXPECT_EQ(log.entries[0].second.failureKind, "");
+}
+
+// A corrupt row is OUR bug, not the tenant's, and it must not be reported as
+// one. This is the case that reaches complete() without the engine running.
+TEST(FailureKind, ARowWithNoFunctionIdIsMalformedNotAFunctionFault) {
+    FakeSource source;
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    queue.pending.push_back(job("j1", ""));
+    JobWorker worker(service, queue, log, workerOptions());
+
+    EXPECT_TRUE(worker.runOnce());
+    ASSERT_EQ(queue.completed.size(), 1u);
+    EXPECT_EQ(queue.completed[0].failureKind, "malformed");
+}

+ 19 - 2
src/function_jobs.cpp

@@ -80,6 +80,7 @@ FunctionJob FunctionJob::fromJson(const nlohmann::json& j) {
     job.runAfter  = j.value("run_after", 0ull);
     job.createdAt = j.value("created_at", 0ull);
     job.lastError = j.value("last_error", "");
+    job.lastFailureKind = j.value("last_failure_kind", "");
     return job;
 }
 
@@ -99,7 +100,8 @@ nlohmann::json FunctionJob::toJson() const {
             {"depth", depth},
             {"run_after", runAfter},
             {"created_at", createdAt},
-            {"last_error", lastError}};
+            {"last_error", lastError},
+            {"last_failure_kind", lastFailureKind}};
 }
 
 FunctionJobQueue::FunctionJobQueue(DbGateway& db) : db_(db) {}
@@ -189,15 +191,19 @@ std::optional<FunctionJob> FunctionJobQueue::claimNext(const std::string& runner
 }
 
 bool FunctionJobQueue::complete(const FunctionJob& job, bool ok, const std::string& error,
-                                 uint32_t retryAfterSec) {
+                                 uint32_t retryAfterSec, const std::string& failureKind) {
     if (job.jobId.empty()) return false;
     FunctionJob next = job;
     if (ok) {
         next.state = "done";
         next.lastError.clear();
+        // Cleared with the error, or a job that failed once and then succeeded
+        // would read as a failure of that kind forever.
+        next.lastFailureKind.clear();
     } else if (retryAfterSec > 0) {
         next.state    = "pending";
         next.lastError = error;
+        next.lastFailureKind = failureKind;
         next.runAfter = nowSec() + retryAfterSec;
         // Clear the claim: a pending row that still carries a claim timestamp
         // would be picked up by reclaimStale and have its backoff cancelled.
@@ -206,6 +212,7 @@ bool FunctionJobQueue::complete(const FunctionJob& job, bool ok, const std::stri
     } else {
         next.state    = "failed";
         next.lastError = error;
+        next.lastFailureKind = failureKind;
     }
     // `attempts` is deliberately left as it is, including on success: it is the
     // history of the job, and the admin list shows "succeeded on attempt 3".
@@ -260,10 +267,20 @@ uint32_t FunctionJobQueue::reclaimStale(uint32_t timeoutSec, uint32_t maxAttempt
             job.state = "failed";
             job.lastError = "abandoned by runner '" + job.claimedBy + "' after " +
                             std::to_string(job.attempts) + " attempt(s)";
+            // A kind the runner's enum does not have, because the runner that
+            // would have classified it is the thing that died. It is OUR
+            // fault, not the function's: routing an abandoned job to the same
+            // alarm as a script that threw would have an operator debugging
+            // the tenant's JavaScript after a host was OOM-killed.
+            job.lastFailureKind = "abandoned";
         } else {
             job.state = "pending";
             job.lastError = "reclaimed from runner '" + job.claimedBy +
                             "': claim went stale";
+            // NOT terminal - it is going back to pending for another attempt -
+            // so the kind records why this attempt ended without claiming the
+            // job failed.
+            job.lastFailureKind = "reclaimed";
             job.claimedBy.clear();
             job.claimedAt = 0;
             job.runAfter  = now;  // due immediately; attempts is NOT rewound

+ 39 - 1
src/function_jobs.hpp

@@ -48,6 +48,44 @@ struct FunctionJob {
     uint64_t runAfter = 0;
     uint64_t createdAt = 0;
     std::string lastError;
+    /// WHY it last failed, as a stable name ("function_fault",
+    /// "runner_fault", "transient_lookup", "malformed"); empty when it has not
+    /// failed.
+    ///
+    /// The worker always classified the failure and then threw the
+    /// classification away, storing only the state and a message - so a failed
+    /// job recorded THAT it failed and a string, and nothing an operator or an
+    /// error handler could branch on. "The runner was full" and "your function
+    /// threw" need different people to do different things, and a free-text
+    /// message cannot be matched on without the text-matching this codebase
+    /// forbids elsewhere for good reason.
+    ///
+    /// A string, not an enum ordinal: an ordinal renumbers when a kind is
+    /// inserted, and a row written last week would start reading as a
+    /// different failure. Also a string so this header keeps knowing nothing
+    /// about the runner's enum, which lives in a layer that must not reach the
+    /// database client.
+    std::string lastFailureKind;
+    ///
+    /// THE COMPLETE SET, which is append-only:
+    ///   `function_fault`    - the script threw, returned a non-response, blew
+    ///                         its memory ceiling, is disabled or will not
+    ///                         compile. The TENANT'S problem. Never retried.
+    ///   `runner_fault`      - no free runtime, host bindings unavailable, an
+    ///                         exception out of the service. OURS. Retried.
+    ///   `transient_lookup`  - the registry answered "no such function", which
+    ///                         today also covers a failed registry read.
+    ///   `malformed`         - the request the worker built was rejected, or
+    ///                         the row carries no project or function id. Our
+    ///                         bug or a corrupt row.
+    ///   `abandoned`         - a runner died holding the claim and the attempt
+    ///                         budget is spent. Set by the QUEUE, not the
+    ///                         runner, because the thing that would have
+    ///                         classified it is what died. Also ours.
+    ///   `reclaimed`         - a stale claim went back to pending. Not
+    ///                         terminal; the job has not failed.
+    ///   `unknown`           - a kind written by a newer runner than this
+    ///                         reader. Recorded honestly rather than guessed.
 
     /// The row version this job was claimed at. Set by claimNext, and what
     /// makes complete() safe.
@@ -111,7 +149,7 @@ public:
     /// A false return means "somebody else owns this now", not "the database
     /// is down"; the caller should log it rather than retry.
     bool complete(const FunctionJob& job, bool ok, const std::string& error,
-                  uint32_t retryAfterSec = 0);
+                  uint32_t retryAfterSec = 0, const std::string& failureKind = {});
 
     /// Return claims older than `timeoutSec` to pending. This is the only thing
     /// that recovers work from a runner that died holding a job, so it has to

+ 7 - 0
src/function_run_log.cpp

@@ -49,6 +49,7 @@ FunctionRunLog FunctionRunLog::fromJson(const nlohmann::json& j) {
     e.status     = j.value("status", 0);
     e.durationMs = j.value("duration_ms", static_cast<int64_t>(0));
     e.error      = j.value("error", "");
+    e.failureKind = j.value("failure_kind", "");
     if (j.contains("console") && j.at("console").is_array()) {
         const nlohmann::json& lines = j.at("console");
         for (const auto& line : lines)
@@ -74,6 +75,12 @@ nlohmann::json FunctionRunLog::toJson() const {
     // invocation, so an always-present empty object is thousands of bytes of
     // nothing.
     if (headers.is_object() && !headers.empty()) j["headers"] = headers;
+    // Same reasoning as `headers`: written only when there IS one, which means
+    // never on a successful run - and most runs succeed. Note this makes an
+    // ABSENT `failure_kind` mean "no failure, or a server older than this
+    // release", which is acceptable only because `ok` already answers the
+    // first question unambiguously.
+    if (!failureKind.empty()) j["failure_kind"] = failureKind;
     return j;
 }
 

+ 9 - 0
src/function_run_log.hpp

@@ -16,6 +16,15 @@ struct FunctionRunLog {
     int status = 0;
     int64_t durationMs = 0;
     std::string error;
+    /// WHY it failed, as a stable name - see `FunctionJob::lastFailureKind`
+    /// for the set. Empty for a successful run and for an HTTP run, which has
+    /// no queue to classify it.
+    ///
+    /// On the log as well as the queue row because the queue row is DELETED
+    /// when a job is reaped, while the run log is what an operator and a
+    /// dashboard actually read. Storing it only on the queue would mean the
+    /// classification survived exactly as long as nobody needed it.
+    std::string failureKind;
     std::vector<std::string> console;
     /// The response headers the function set. Present so a client can render a
     /// logged run with the same component as a fresh invoke envelope, which

+ 42 - 0
webui/src/pages/Functions.tsx

@@ -912,6 +912,28 @@ function ConsoleView({ lines }: { lines: string[] }) {
 
 // ─── runs tab ─────────────────────────────────────────────────────────────────
 
+/// How a failure kind should READ to an operator, and whose problem it is.
+///
+/// The colour carries the only question worth answering at a glance: a
+/// `function_fault` is the script's own doing and a `runner_fault` or an
+/// `abandoned` job is OURS. Rendering both in the same red is how an operator
+/// learns to debug the tenant's JavaScript after a host was OOM-killed.
+function failureKindLabel(kind: string): { text: string; ours: boolean } | null {
+  switch (kind) {
+    case 'function_fault':   return { text: 'function', ours: false }
+    case 'runner_fault':     return { text: 'runner', ours: true }
+    case 'abandoned':        return { text: 'runner died', ours: true }
+    case 'transient_lookup': return { text: 'lookup', ours: true }
+    case 'malformed':        return { text: 'bad job row', ours: true }
+    case 'reclaimed':        return { text: 'retrying', ours: true }
+    case '':                 return null
+    // A kind this build does not know, from a newer server. Shown verbatim
+    // rather than hidden: an unrecognised cause is still a cause, and
+    // swallowing it would make a new failure mode invisible in the UI.
+    default:                 return { text: kind, ours: true }
+  }
+}
+
 function RunsTab({ project, fn, runsKept }: { project: string; fn: FunctionSummary; runsKept: number }) {
   const [limit, setLimit] = useState(50)
   const [open, setOpen] = useState('')
@@ -1018,6 +1040,26 @@ function RunsTab({ project, fn, runsKept }: { project: string; fn: FunctionSumma
                       >
                         {r.ok ? 'ok' : 'failed'}
                       </span>
+                      {/* WHY it failed, when the server said. Absent on an
+                          older server, which is why `ok` above is the field
+                          that decides the red badge. */}
+                      {!r.ok && failureKindLabel(r.failure_kind ?? '') && (
+                        <span
+                          className={[
+                            'ml-1.5 inline-block px-2 py-0.5 rounded text-xs font-medium border',
+                            failureKindLabel(r.failure_kind ?? '')!.ours
+                              ? 'bg-amber-500/15 text-amber-300 border-amber-500/30'
+                              : 'bg-slate-500/15 text-slate-300 border-slate-500/30',
+                          ].join(' ')}
+                          title={
+                            failureKindLabel(r.failure_kind ?? '')!.ours
+                              ? 'Not the function: this failure is the runner or the queue.'
+                              : 'The function itself failed.'
+                          }
+                        >
+                          {failureKindLabel(r.failure_kind ?? '')!.text}
+                        </span>
+                      )}
                     </td>
                     <td className="px-4 py-2.5 text-xs font-mono text-slate-300">{r.status}</td>
                     <td className="px-4 py-2.5 text-xs font-mono text-slate-400">{r.duration_ms} ms</td>

+ 6 - 0
webui/src/types/index.ts

@@ -273,6 +273,12 @@ export interface FunctionRun {
   status: number
   duration_ms: number
   error: string
+  /// WHY it failed, when the server knows: "function_fault" (the script's
+  /// fault), "runner_fault" / "abandoned" (ours), "transient_lookup",
+  /// "malformed", "reclaimed". ABSENT on a successful run AND on a server
+  /// older than this release, so never read its absence as "no failure" -
+  /// `ok` is the field that answers that.
+  failure_kind?: string
   console: string[]
   started_at: number
 }