Find and Resubmit Failed Jobs¶
An operations team runs nightly import jobs and RPA automations. When a job fails or stops being picked up, nobody notices until a business user asks where the morning's documents are, and then someone opens Monitor and restarts it by hand. This recipe is a watchdog that runs every few minutes: it finds failed and stalled scheduled jobs and failed RPA tasks, reports why they failed, and resubmits the ones you allow, with guards so it never loops.
At a glance
- Extension point REST API from your own code, run on a schedule (Task Scheduler, cron, an Azure Function timer)
- You need A token with Query Jobs, Manage Jobs, Get Bots and Manage Bots; the names of the jobs and automations that are safe to rerun
- Teaches The
V1_JobsAPIandV1_RPAAPIactions, paging without a total count, safe automatic retries (allowlist, cooldown, cap), and an exit code a scheduler can alert on
graph TD
S["Scheduler starts the watchdog"] --> J["QueryForJobRuns: JobStatus Error"]
S --> T["QueryForJobRuns: Active, NextRuntime long past"]
S --> R["QueryForLatestRPATasks: Status Error"]
J --> H["QueryForJobHistories: read ExceptionMessage"]
H --> G{"On allowlist and out of cooldown?"}
R --> G
G -->|"yes, with --apply"| X["ResubmitJob or ResubmitRPATask"]
G -->|"no"| P["Report only"]
T --> P
X --> E["Exit code 1 when anything needs a person"]
P --> E
Set it up¶
- Create a service account. In Configuration > Permissions > API Access, give it Query Jobs, Manage Jobs, Get Bots and Manage Bots.
- Sign in as the account and create a token with the same four features in Configuration > Services > API Access. For a report-only watchdog, leave out Manage Jobs and Manage Bots.
- For C#, create a console app (
dotnet new console) and generateKL.APIClientfrom your tenant's spec and reference it. See Generate the client. For Python, install Python 3.9 or later and runpip install requests. - Set
KL_BASE_URL(for examplehttps://yourcompany.knowledgelake.io/api) andKL_API_TOKENin the environment. - Edit
RERUNNABLE_JOBSandRERUNNABLE_AUTOMATIONSat the top of the script (rerunnableJobsandrerunnableAutomationsin C#). List only jobs and automations that are safe to run twice. Leave a set empty to report only. - Schedule the script every 15 minutes. For C#, schedule
dotnet runin the folder of the console app, or the program thatdotnet publishmakes. Send its output to your log, and alert when the exit code is 1.
The script¶
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using KL.APIClient.Api;
using KL.APIClient.Client;
using KL.APIClient.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var cli = Environment.GetCommandLineArgs().Skip(1).ToArray();
bool apply = cli.Contains("--apply"); // without it, report only
var rerunnableJobs = new HashSet<string> { "Import File", "Import Email" }; // job display names safe to rerun
var rerunnableAutomations = new HashSet<string> { "Vendor Portal Download" }; // RPA automations safe to rerun
var lookback = TimeSpan.FromHours(24); // how far back to look for failures
var stallGrace = TimeSpan.FromMinutes(30); // an Active job whose next run is this late is reported
var cooldown = TimeSpan.FromHours(6); // never resubmit the same item more often than this
const int MaxResubmits = 5; // per run, across jobs and RPA tasks
const string StateFile = "job-watchdog-state.json"; // remembers what was resubmitted and when
const int Page = 200;
var config = new Configuration
{
BasePath = Environment.GetEnvironmentVariable("KL_BASE_URL").TrimEnd('/'),
Timeout = TimeSpan.FromSeconds(120)
};
config.AddApiKey("TempIdentityToken", Environment.GetEnvironmentVariable("KL_API_TOKEN"));
var jobs = new V1JobsAPIApi(config);
var rpa = new V1RPAAPIApi(config);
try
{
Environment.ExitCode = await Run();
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Environment.ExitCode = 1;
}
async Task<int> Run()
{
var now = DateTimeOffset.UtcNow;
var since = now - lookback;
var state = LoadState();
int resubmits = 0, needsPerson = 0;
// 1. Scheduled jobs in Error.
await foreach (var job in Pages(index => JobRuns(JobStatus.Error, index)))
{
string name = job.JobDisplayName;
Guid jobId = job.JobID;
string reason = await LastError(jobId, since);
string key = $"job:{jobId}";
if (rerunnableJobs.Contains(name) && !InCooldown(state, key, now) && resubmits < MaxResubmits)
{
if (apply)
{
var r = await Call("V1_JobsAPI/ResubmitJob", () => jobs.V1JobsAPIControllerResubmitJobAsync(
new RunJobParameter { JobInstanceID = jobId }));
Check("V1_JobsAPI/ResubmitJob", r.Success, r.MessageKey);
state[key] = now;
resubmits++;
}
Console.WriteLine($"JOB FAILED {name} ({jobId}) {(apply ? "resubmitted" : "would resubmit")}: {reason}");
}
else
{
needsPerson++;
Console.WriteLine($"JOB FAILED {name} ({jobId}) needs a person: {reason}");
}
}
// 2. Active jobs whose next run time passed long ago: report, never resubmit automatically.
await foreach (var job in Pages(index => JobRuns(JobStatus.Active, index)))
{
if (job.NextRuntime.HasValue && now.UtcDateTime - Utc(job.NextRuntime.Value) > stallGrace)
{
needsPerson++;
Console.WriteLine($"JOB LATE {job.JobDisplayName} ({job.JobID}) next run was {Utc(job.NextRuntime.Value):o}");
}
}
// 3. RPA tasks in Error, updated inside the lookback window.
// LastUpdateTimeAfter is compared exactly as sent: send it to the second, with no time zone.
var after = DateTime.SpecifyKind(since.UtcDateTime, DateTimeKind.Unspecified);
after = after.AddTicks(-(after.Ticks % TimeSpan.TicksPerSecond));
await foreach (var task in Pages(index => FailedTasks(after, index)))
{
string tid = task.TaskIdentifier, automation = task.Automation ?? "";
string key = "rpa:" + tid.Split('.')[0];
if (rerunnableAutomations.Contains(automation) && !InCooldown(state, key, now) && resubmits < MaxResubmits)
{
if (apply)
{
var r = await Call("V1_RPAAPI/ResubmitRPATask", () => rpa.V1RPAAPIControllerResubmitRPATaskAsync(
new ResumbitRPATasksParameter { TaskIdentifier = tid }));
Check("V1_RPAAPI/ResubmitRPATask", r.Success, r.MessageKey);
state[key] = now;
resubmits++;
}
Console.WriteLine($"RPA FAILED {automation} task {tid} {(apply ? "resubmitted" : "would resubmit")}: {task.Message}");
}
else
{
needsPerson++;
Console.WriteLine($"RPA FAILED {automation} task {tid} on {task.BotName} needs a person: {task.Message}");
}
}
File.WriteAllText(StateFile, JsonConvert.SerializeObject(state, Formatting.Indented));
Console.WriteLine($"Done: {resubmits} resubmitted, {needsPerson} need a person, apply = {apply}");
return needsPerson > 0 ? 1 : 0;
}
// Send one call and return the response, or throw with the API's message text.
async Task<T> Call<T>(string action, Func<Task<T>> send)
{
try
{
return await send();
}
catch (ApiException e)
{
throw new Exception($"{action}: HTTP {e.ErrorCode} {Messages(e)}", e);
}
}
// HTTP 200 with Success false.
void Check(string action, bool success, string messageKey)
{
if (!success) throw new Exception($"{action}: HTTP 200 {messageKey}");
}
// Read Messages[].MessageKey from the failure envelope in the response body.
string Messages(ApiException e)
{
string body = e.ErrorContent?.ToString() ?? "";
try
{
var envelope = JObject.Parse(body);
var keys = (envelope["Messages"] as JArray ?? new JArray())
.Select(m => (string)m["MessageKey"] ?? "").ToList();
return keys.Count > 0 ? string.Join("; ", keys) : (string)envelope["MessageKey"] ?? "";
}
catch (JsonException)
{
return body.Length > 300 ? body.Substring(0, 300) : body;
}
}
// Yield every row. These queries return no total, so stop at a short page.
async IAsyncEnumerable<T> Pages<T>(Func<int, Task<List<T>>> fetchPage)
{
for (int index = 0; ; index++)
{
var rows = await fetchPage(index) ?? new List<T>();
foreach (var row in rows) yield return row;
if (rows.Count < Page) yield break;
await Task.Delay(250);
}
}
async Task<List<JobRunDTO>> JobRuns(JobStatus status, int index)
{
var r = await Call("V1_JobsAPI/QueryForJobRuns", () => jobs.V1JobsAPIControllerQueryForJobRunsAsync(
new FilterJobParameter { JobStatus = status, PageIndex = index, PageSize = Page }));
Check("V1_JobsAPI/QueryForJobRuns", r.Success, r.MessageKey);
return r.Data;
}
async Task<List<RPATaskEntryDTO>> FailedTasks(DateTime updatedAfter, int index)
{
var r = await Call("V1_RPAAPI/QueryForLatestRPATasks", () => rpa.V1RPAAPIControllerQueryForLatestRPATasksAsync(
new QueryRPATasksParameter { Status = RPATaskStatus.Error, LastUpdateTimeAfter = updatedAfter, PageIndex = index, PageSize = Page }));
Check("V1_RPAAPI/QueryForLatestRPATasks", r.Success, r.MessageKey);
return r.Data;
}
// Read an API date-time as UTC. A value with no time zone is taken as UTC.
DateTime Utc(DateTime value) =>
value.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(value, DateTimeKind.Utc) : value.ToUniversalTime();
Dictionary<string, DateTimeOffset> LoadState()
{
try
{
return JsonConvert.DeserializeObject<Dictionary<string, DateTimeOffset>>(File.ReadAllText(StateFile))
?? new Dictionary<string, DateTimeOffset>();
}
catch (Exception e) when (e is IOException || e is JsonException)
{
return new Dictionary<string, DateTimeOffset>();
}
}
bool InCooldown(Dictionary<string, DateTimeOffset> state, string key, DateTimeOffset now) =>
state.TryGetValue(key, out var last) && now - last < cooldown;
// Return the newest history entry with an exception message for one job.
async Task<string> LastError(Guid jobId, DateTimeOffset since)
{
var r = await Call("V1_JobsAPI/QueryForJobHistories", () => jobs.V1JobsAPIControllerQueryForJobHistoriesAsync(
new FilterJobHistoryParameter { JobID = jobId, EntryDateOnOrAfter = since.UtcDateTime, Take = 50 }));
Check("V1_JobsAPI/QueryForJobHistories", r.Success, r.MessageKey);
var newest = (r.Data ?? new List<JobHistoryDTO>())
.Where(entry => !string.IsNullOrEmpty(entry.ExceptionMessage))
.OrderByDescending(entry => Utc(entry.EntryDate))
.FirstOrDefault();
return newest?.ExceptionMessage ?? "(no exception message in history)";
}
import json
import os
import sys
import time
from datetime import datetime, timedelta, timezone
import requests
BASE = os.environ["KL_BASE_URL"].rstrip("/")
HEADERS = {"TempIdentityToken": os.environ["KL_API_TOKEN"]}
APPLY = "--apply" in sys.argv # without it, report only
RERUNNABLE_JOBS = {"Import File", "Import Email"} # job display names safe to rerun
RERUNNABLE_AUTOMATIONS = {"Vendor Portal Download"} # RPA automations safe to rerun
LOOKBACK = timedelta(hours=24) # how far back to look for failures
STALL_GRACE = timedelta(minutes=30) # an Active job whose next run is this late is reported
COOLDOWN = timedelta(hours=6) # never resubmit the same item more often than this
MAX_RESUBMITS = 5 # per run, across jobs and RPA tasks
STATE_FILE = "job-watchdog-state.json" # remembers what was resubmitted and when
PAGE = 200
def call(action, body):
"""POST one action and return Data, or raise with the API's message text."""
r = requests.post(f"{BASE}/{action}", headers=HEADERS, json=body, timeout=120)
try:
env = r.json()
except ValueError:
raise RuntimeError(f"{action}: HTTP {r.status_code} {r.text[:300]}")
if r.status_code == 200 and env.get("Success"):
return env.get("Data")
msgs = [m.get("MessageKey", "") for m in env.get("Messages", [])] or [env.get("MessageKey", "")]
raise RuntimeError(f"{action}: HTTP {r.status_code} {'; '.join(msgs)}")
def pages(action, body, index_key="PageIndex", size_key="PageSize"):
"""Yield every row. These queries return no total, so stop at a short page."""
index = 0
while True:
rows = call(action, dict(body, **{index_key: index, size_key: PAGE})) or []
yield from rows
if len(rows) < PAGE:
return
index += 1
time.sleep(0.25)
def parse_time(value):
"""Parse an API date-time such as 2026-10-07T20:19:08.9196097+00:00."""
if not value:
return None
text = value.replace("Z", "+00:00")
if "." in text:
head, rest = text.split(".", 1)
digits = "".join(c for c in rest if c.isdigit())
zone = rest[len(digits):]
text = f"{head}.{digits[:6]}{zone}"
parsed = datetime.fromisoformat(text)
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
def load_state():
try:
with open(STATE_FILE, encoding="utf-8") as f:
return json.load(f)
except (OSError, ValueError):
return {}
def in_cooldown(state, key, now):
last = state.get(key)
return last is not None and now - parse_time(last) < COOLDOWN
def last_error(job_id, since):
"""Return the newest history entry with an exception message for one job."""
entries = call("V1_JobsAPI/QueryForJobHistories", {
"JobID": job_id, "EntryDateOnOrAfter": since.isoformat(), "Take": 50,
}) or []
failed = [e for e in entries if e.get("ExceptionMessage")]
failed.sort(key=lambda e: parse_time(e["EntryDate"]), reverse=True)
return failed[0]["ExceptionMessage"] if failed else "(no exception message in history)"
def main():
now = datetime.now(timezone.utc)
since = now - LOOKBACK
state = load_state()
resubmits, needs_person = 0, 0
# 1. Scheduled jobs in Error.
for job in pages("V1_JobsAPI/QueryForJobRuns", {"JobStatus": "Error"}):
name, job_id = job["JobDisplayName"], job["JobID"]
reason = last_error(job_id, since)
key = f"job:{job_id}"
if name in RERUNNABLE_JOBS and not in_cooldown(state, key, now) and resubmits < MAX_RESUBMITS:
if APPLY:
call("V1_JobsAPI/ResubmitJob", {"JobInstanceID": job_id})
state[key] = now.isoformat()
resubmits += 1
print(f"JOB FAILED {name} ({job_id}) {'resubmitted' if APPLY else 'would resubmit'}: {reason}")
else:
needs_person += 1
print(f"JOB FAILED {name} ({job_id}) needs a person: {reason}")
# 2. Active jobs whose next run time passed long ago: report, never resubmit automatically.
for job in pages("V1_JobsAPI/QueryForJobRuns", {"JobStatus": "Active"}):
next_run = parse_time(job.get("NextRuntime"))
if next_run and now - next_run > STALL_GRACE:
needs_person += 1
print(f"JOB LATE {job['JobDisplayName']} ({job['JobID']}) next run was {job['NextRuntime']}")
# 3. RPA tasks in Error, updated inside the lookback window.
rpa_body = {"Status": "Error", "LastUpdateTimeAfter": since.strftime("%Y-%m-%dT%H:%M:%S")}
for task in pages("V1_RPAAPI/QueryForLatestRPATasks", rpa_body):
tid, automation = task["TaskIdentifier"], task.get("Automation") or ""
key = f"rpa:{tid.split('.')[0]}"
if automation in RERUNNABLE_AUTOMATIONS and not in_cooldown(state, key, now) and resubmits < MAX_RESUBMITS:
if APPLY:
call("V1_RPAAPI/ResubmitRPATask", {"TaskIdentifier": tid})
state[key] = now.isoformat()
resubmits += 1
print(f"RPA FAILED {automation} task {tid} {'resubmitted' if APPLY else 'would resubmit'}: {task.get('Message')}")
else:
needs_person += 1
print(f"RPA FAILED {automation} task {tid} on {task.get('BotName')} needs a person: {task.get('Message')}")
with open(STATE_FILE, "w", encoding="utf-8") as f:
json.dump(state, f, indent=2)
print(f"Done: {resubmits} resubmitted, {needs_person} need a person, apply = {APPLY}")
return 1 if needs_person else 0
if __name__ == "__main__":
sys.exit(main())
$KLBase = "https://yourcompany.knowledgelake.io/api"
$KLHeaders = @{ TempIdentityToken = $env:KnowledgeLakeApiToken }
function Invoke-KL([string]$Action, [hashtable]$Body) {
$r = Invoke-RestMethod -Method Post -Uri "$KLBase/$Action" -Headers $KLHeaders `
-ContentType "application/json" -Body ($Body | ConvertTo-Json -Depth 10)
if (-not $r.Success) { throw "$Action failed: $($r.MessageKey)" }
return $r.Data
}
$since = (Get-Date).ToUniversalTime().AddHours(-24).ToString("o")
$failed = Invoke-KL "V1_JobsAPI/QueryForJobRuns" @{ JobStatus = "Error"; PageSize = 200 }
foreach ($job in $failed) {
$history = Invoke-KL "V1_JobsAPI/QueryForJobHistories" @{ JobID = $job.JobID; EntryDateOnOrAfter = $since; Take = 50 }
$reason = ($history | Where-Object { $_.ExceptionMessage } |
Sort-Object { [datetime]$_.EntryDate } -Descending | Select-Object -First 1).ExceptionMessage
[pscustomobject]@{ Job = $job.JobDisplayName; JobID = $job.JobID; LastRun = $job.LastRuntime; Reason = $reason }
}
# To resubmit one job after you checked it:
# Invoke-KL "V1_JobsAPI/ResubmitJob" @{ JobInstanceID = "<JobID from the list>" }
How it works¶
The C# program and the Python script do the same steps. Where the names differ, the C# name follows in parentheses.
- Failed jobs.
QueryForJobRunswithJobStatusErrorlists every job in Error.JobIDin the result is the job instance id thatResubmitJobtakes asJobInstanceID. - Why it failed.
QueryForJobHistoriesfor thatJobIDreturns the run history; the newest entry with anExceptionMessageis the reason. The script prints it, so the alert already says what broke. - Late jobs. An
Activejob whoseNextRuntimeis more thanSTALL_GRACE(stallGrace) in the past has not been picked up. That is the silent stall pattern. The script reports it and never resubmits it, because the cause (a stopped worker, a held lock) needs a person. - Failed RPA tasks.
QueryForLatestRPATaskswithStatusErrorreturns the latest run of each task.ResubmitRPATaskreruns it with its original payload. - Safe retries. A rerun happens only with
--apply, only for names on the allowlist, at most once perCOOLDOWN(cooldown) for the same item (kept injob-watchdog-state.json), and at mostMAX_RESUBMITS(MaxResubmits) per run. A job that fails every time is retried a few times a day, then stays on the report. - Paging. None of these queries returns a total.
pages(Pages) asks for 200 rows at a time and stops at a short page. - Alerting. The exit code is 1 when anything needs a person, so the scheduler can raise the alert.
Test it¶
- Run the watchdog without
--apply:dotnet runfor C#, orpython job_watchdog.py. Compare theJOB FAILEDlines with Monitor > All Jobs filtered to Error. - Pick one failed job that is safe to rerun. Put its display name in
RERUNNABLE_JOBS(rerunnableJobsin C#) and run it with--apply:dotnet run -- --applyfor C#, orpython job_watchdog.py --apply. - Run it with
--applyagain at once.
You should see
in step 2 one resubmitted line for that job and a new run in Monitor > Jobs History. In step 3 the same job, if it is still in Error, shows as needs a person because it is in its cooldown, and the exit code is 1.
What can go wrong¶
| What you see | Cause and fix |
|---|---|
| HTTP 401 on one action only | The token is missing that action's feature. Query actions need Query Jobs or Get Bots; resubmits need Manage Jobs or Manage Bots. |
| A job reruns and fails again | The cause is still there (a missing file share, an expired credential). Read the reason, fix it, then resubmit. The cooldown stops the watchdog from hammering it. |
| A job is not safe to run twice | An export or a purge can duplicate or destroy data. Keep such jobs off RERUNNABLE_JOBS. |
| No RPA tasks come back, although Monitor shows failures | LastUpdateTimeAfter is compared exactly as sent, with no time zone conversion. Send it in the zone the tasks were recorded in, or widen LOOKBACK. |
| An RPA filter is rejected | An unknown BotName or Automation, or a blank Process, is refused, not ignored. |
JobDisplayName filters behave differently |
QueryForJobRuns compares the name without case, QueryForJobHistories with case. The script filters by JobID to avoid this. |
Bot failed to restart |
The RPA service could not restart the task. Check the bot in Monitor. |
Variations¶
- Report to a channel. Replace the
printcalls with a post to your team's chat or incident tool. - Watch work items too.
V1_ProcessingAPI/QueryForWorkItemswithStatusErrorlists work items in Error in the processing monitor. See Jobs, RPA and Monitoring API. - Push instead of poll. With a Secondary Event Provider, the
processing, job, error, ExecuteJobandbotServices, consumption, finishBotAutomationevents arrive in your own store as jobs fail. See the Events Dictionary.